首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AttributeError:“列表”对象没有属性“get_label”

AttributeError:“列表”对象没有属性“get_label”
EN

Stack Overflow用户
提问于 2022-06-14 10:07:15
回答 2查看 635关注 0票数 0

我试着用两个y轴和一个x轴来绘制基本图。为了获得不同曲线的图例信息,我得到了AttributeError。这是我的代码:

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2.0*np.pi, 101)
y = np.sin(x)
z = np.sinh(x)

# separate the figure object and axes object from the plotting object
fig, ax1 = plt.subplots()

# Duplicate the axes with a differebt y axis and the same x axis
ax2 = ax1.twinx()  # ax2 and ax1 will have common x axis and different y axis

# plot the curves on axes 1, and 2 and get the curve hadles
curve1 = ax1.plot(x, y, label="sin", color='r')
curve2 = ax2.plot(x, z, label="sinh", color='b')

# Make a curves list to access the parameters in the curves
curves = [curve1, curve2]

# Add legend via axes1 or axex 2 object.
# ax1.legend() will not display the legend of ax2
# ax2.legend() will not display the legend of ax1

ax1.legend(curves, [curve.get_label() for curve in curves])
#ax2.legend(curves, [curve.get_label() for curve in curves]) also valid

# Global figure properties
plt.title("Plot of sine and hyperbolic sine")
plt.show()

我在下面的线上出错了:

代码语言:javascript
复制
ax1.legend(curves, [curve.get_label() for curve in curves])

如果有人知道为什么会发生,请告诉我。

EN

回答 2

Stack Overflow用户

发布于 2022-06-14 10:39:47

这将解决您的问题,尝试如下:

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2.0*np.pi, 101)
y = np.sin(x)
z = np.sinh(x)

# separate the figure object and axes object from the plotting object
fig, ax1 = plt.subplots()

# Duplicate the axes with a differebt y axis and the same x axis
ax2 = ax1.twinx()  # ax2 and ax1 will have common x axis and different y axis

# plot the curves on axes 1, and 2 and get the curve hadles
curve1 = ax1.plot(x, y, label="sin", color='r')
curve2 = ax2.plot(x, z, label="sinh", color='b')

# Make a curves list to access the parameters in the curves
curves = curve1 + curve2

# Add legend via axes1 or axex 2 object.
# ax1.legend() will not display the legend of ax2
# ax2.legend() will not display the legend of ax1
labs = [curve.get_label() for curve in curves]
ax1.legend(curves, labs, loc=0)

#ax1.legend(curves, [curve.get_label() for curve in curves])
#ax2.legend(curves, [curve.get_label() for curve in curves]) also valid

# Global figure properties
plt.title("Plot of sine and hyperbolic sine")
plt.show()
票数 0
EN

Stack Overflow用户

发布于 2022-06-14 10:31:15

如果您读取拟图文档,您可以看到绘图函数返回一个列表,该列表显然没有方法get_label()

您想要的可能是在matplotlib的图例文档中描述的内容,它是自动检测您的情节的标签。这意味着您不必存储您的行结果,您的图例调用将从

代码语言:javascript
复制
ax1.legend(curves, [curve.get_label() for curve in curves])

简单地

代码语言:javascript
复制
ax1.legend()

在我看来,阅读文档不仅在大多数情况下解决了您的问题,而且在编程世界中给您提供了一种非常重要的能力,即能够自己解决问题(以及阅读文档)。

干杯

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72615116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档