我有一个关于为绘图提供标题和/或标签的问题。 大多数时候我更喜欢使用这样的系统:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [20, 21, 20.5, 20.8]
fig, axarr = plt.subplots(n,m)
axarr[n,m] = plt.plot(x,y)
axarr[n,m].set_xlabel('x label')
axarr[n,m].set_ylabel('y label')
axarr[n,m].set_xlabel('title')
etc
但现在我转换了一个 matlab 脚本,为了尽可能接近,我想尝试一下该系统。 我希望我的代码必须如下所示:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [20, 21, 20.5, 20.8]
ax = plt.plot(x,y)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_xlabel('title')
etc
但是现在标签/标题给出错误AttributeError: 'list' object has no attribute 'set_xlabel'
所以我环顾四周并找到了 https://sites.google.com/site/scigraphs/tutorial下面的代码可以运行。
#import matplotlib libary
import matplotlib.pyplot as plt
#define some data
x = [1,2,3,4]
y = [20, 21, 20.5, 20.8]
#plot data
plt.plot(x, y, linestyle="dashed", marker="o", color="green")
#configure X axes
plt.xlim(0.5,4.5)
plt.xticks([1,2,3,4])
#configure Y axes
plt.ylim(19.8,21.2)
plt.yticks([20, 21, 20.5, 20.8])
#labels
plt.xlabel("this is X")
plt.ylabel("this is Y")
#title
plt.title("Simple plot")
#show plot
plt.show()
所以基本上我的问题是为什么我不能使用中间方法来添加标签或标题(请同时说明为什么),但是我需要子图(方法1)还是示例的方法?
最佳答案
如the documentation for plot()
explains , plot()
返回 Line2D
对象的列表,而不是 Axes
,这就是您的第二个代码不起作用的原因。
本质上,有两种使用 matplotlib 的方法:
- 您可以使用pyplot API (
将 matplotlib.pyplot 导入为 plt
)。然后,每个命令都以plt.xxxxx()
开头,并且它们作用于最后创建的 Axes 对象,您通常不需要显式引用该对象。
您的代码将是:
plt.plot(x,y)
plt.xlabel('x label')
plt.ylabel('y label')
plt.xlabel('title')
- 要么使用面向对象的方法
您的代码将写入的位置:
fig, ax = plt.subplots()
line, = ax.plot(x,y)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_xlabel('title')
通常不建议混合使用这两种方法。 pyplot API 对于从 MATLAB 迁移的人员很有用,但由于存在多个子图,因此很难确定正在处理哪个 Axes,因此建议使用 OO 方法。
参见this part of matplotlib FAQs了解更多信息。
关于python - 向单个绘图添加标题或标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46025476/