在 matplotlib 中向单个图添加标题或标签的正确方法

Right way to add a title or label to a single plot in matplotlib

我有一个关于给情节命名和/或标签的问题。 大多数时候我更喜欢使用这样的系统:

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

但是现在labels/title报错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() explainsplot() returns Line2D 对象的列表,而不是 Axes,这就是为什么您的第二个代码不起作用的原因。

本质上,有两种使用matplotlib的方法:

  • 要么你用pyplot API(import matplotlib.pyplot as 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 迁移过来的人很有用,但是有几个子图,很难确定一个人正在处理哪个轴,因此推荐使用 OO 方法。

有关详细信息,请参阅 this part of matplotlib FAQs