我试着用两个y轴和一个x轴来绘制基本图。为了获得不同曲线的图例信息,我得到了AttributeError。这是我的代码:
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()我在下面的线上出错了:
ax1.legend(curves, [curve.get_label() for curve in curves])如果有人知道为什么会发生,请告诉我。
发布于 2022-06-14 10:39:47
这将解决您的问题,尝试如下:
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()发布于 2022-06-14 10:31:15
如果您读取拟图文档,您可以看到绘图函数返回一个列表,该列表显然没有方法get_label()。
您想要的可能是在matplotlib的图例文档中描述的内容,它是自动检测您的情节的标签。这意味着您不必存储您的行结果,您的图例调用将从
ax1.legend(curves, [curve.get_label() for curve in curves])简单地
ax1.legend()在我看来,阅读文档不仅在大多数情况下解决了您的问题,而且在编程世界中给您提供了一种非常重要的能力,即能够自己解决问题(以及阅读文档)。
干杯
https://stackoverflow.com/questions/72615116
复制相似问题