在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别? [英] What is the difference between drawing plots using plot, axes or figure in matplotlib?

查看:34
本文介绍了在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 matplotlib 中绘制绘图时,我有点困惑后端发生了什么,tbh,我不清楚绘图、轴和图形的层次结构.我阅读了文档,它很有帮助,但我仍然感到困惑...

I'm kind of confused what is going at the backend when I draw plots in matplotlib, tbh, I'm not clear with the hierarchy of plot, axes and figure. I read the documentation and it was helpful but I'm still confused...

下面的代码以三种不同的方式绘制相同的图 -

The below code draws the same plot in three different ways -

#creating the arrays for testing
x = np.arange(1, 100)
y = np.sqrt(x)
#1st way
plt.plot(x, y)
#2nd way
ax = plt.subplot()
ax.plot(x, y)
#3rd way
figure = plt.figure()
new_plot = figure.add_subplot(111)
new_plot.plot(x, y)

现在我的问题是 -

  1. 这三个方法之间有什么区别,我的意思是当调用这 3 个方法中的任何一个时,引擎盖下会发生什么?

  1. What is the difference between all the three, I mean what is going under the hood when any of the 3 methods are called?

什么时候应该使用哪种方法,在这些方法上使用 any 的利弊是什么?

Which method should be used when and what are the pros and cons of using any on those?

推荐答案

方法一

plt.plot(x, y)

这使您可以仅绘制一个具有 (x,y) 坐标的图形.如果你只想得到一个图形,你可以使用这种方式.

This lets you plot just one figure with (x,y) coordinates. If you just want to get one graphic, you can use this way.

方法二

ax = plt.subplot()
ax.plot(x, y)

这让您可以在同一窗口中绘制一个或多个图形.在编写它时,您将只绘制一个图形,但您可以制作如下内容:

This lets you plot one or several figure(s) in the same window. As you write it, you will plot just one figure, but you can make something like this:

fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

您将在同一个窗口上绘制 4 个名为 ax1、ax2、ax3 和 ax4 的图形.在我的例子中,这个窗口将被分为 4 个部分.

You will plot 4 figures which are named ax1, ax2, ax3 and ax4 each one but on the same window. This window will be just divided in 4 parts with my example.

方法三

fig = plt.figure()
new_plot = fig.add_subplot(111)
new_plot.plot(x, y)

我没用过,但你可以找到文档.

I didn't use it, but you can find documentation.

示例:

import numpy as np
import matplotlib.pyplot as plt

# Method 1 #

x = np.random.rand(10)
y = np.random.rand(10)

figure1 = plt.plot(x,y)

# Method 2 #

x1 = np.random.rand(10)
x2 = np.random.rand(10)
x3 = np.random.rand(10)
x4 = np.random.rand(10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)

figure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot(x1,y1)
ax2.plot(x2,y2)
ax3.plot(x3,y3)
ax4.plot(x4,y4)

plt.show()

其他示例:

这篇关于在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆