python - 向单个绘图添加标题或标签

标签 python matplotlib title axis-labels

我有一个关于为绘图提供标题和/或标签的问题。 大多数时候我更喜欢使用这样的系统:

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() explainsplot() 返回 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/

相关文章:

ios - 更改 UINavigationController 标题的字体

php - 布伦特里交易

python ,C : How to access methods written in C through Python?

python - Pybrain 神经网络无法正确训练

python - 针对每个 HTTP 方法的 Flask-RESTful 自定义路由

python interactive plot 最新的颜色线,其余为黑色

python - 将 x 轴刻度标签向左移动一位

Python 和 Matplotlib : characters as the x axis

ios - self.PresentingViewController.title 是 [null]

objective-c - 在 Interface Builder 中更改窗口标题