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

查看:79
本文介绍了在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. 这三种方法之间有什么区别,我的意思是当调用这三种方法中的任何一种时,幕后情况如何?

  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?

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

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

推荐答案

方法1

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.

方法2

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,但在同一窗口上.在我的示例中,该窗口将分为四个部分.

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.

方法3

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天全站免登陆