为什么所有标签在matplotlib中都无法正确显示?

时间:2020-01-09 21:39:48

标签: python python-3.x matplotlib

当我执行以下代码时,我可以看到Demo在水平顶部打印。 Demo2使用dotted line在图内打印。但是我看不到Demo1吗? 为什么Demo1不打印,为什么Demo水平打印?

import matplotlib.pyplot as plt    
x = [1,2,3,4,5,-1-2]
y = [-1,5, 100, -2, 50, 100]
t = [100, 110, 120, 130, 140, 150]
plt.figure()

ax1 = plt.subplot(3, 1, 1)
plt.title('Demo');
ax1.plot(t,x, 'b.:', label="Demo") # Showing top Horizontal 

ax2 = plt.subplot(3, 1, 2, sharex=ax1)
ax2.plot(t,y, 'b.:', label="Demo1") # Not showing up

ax3 = plt.subplot(3, 1, 3, sharex=ax1)
ax3.plot(t,t, 'b.:', label="Demo2") # This is perfect how I wanted

plt.legend()
plt.show()

1 个答案:

答案 0 :(得分:1)

您可以改用plt.figlegend(),这样将为您提供输出

enter image description here

或在每个绘图后调用plt.legend(),将图例分别添加到每个子绘图中,

import matplotlib.pyplot as plt    
x = [1,2,3,4,5,-1-2]
y = [-1,5, 100, -2, 50, 100]
t = [100, 110, 120, 130, 140, 150]
plt.figure()

ax1 = plt.subplot(3, 1, 1)
plt.title('Demo');
ax1.plot(t,x, 'b.:', label="Demo") # Showing top Horizontal 
plt.legend()

ax2 = plt.subplot(3, 1, 2, sharex=ax1)
ax2.plot(t,y, 'b.:', label="Demo1") # Not showing up
plt.legend()

ax3 = plt.subplot(3, 1, 3, sharex=ax1)
ax3.plot(t,t, 'b.:', label="Demo2") # This is perfect how I wanted
plt.legend()
plt.show()

enter image description here

如果这不是您想要的,this question的答案中还列出了其他方法