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

2024-09-29 00:16:43 发布

您现在位置:Python中文网/ 问答频道 /正文

当我执行下面的代码时,我可以看到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()

Tags: 代码plotdemoline水平pltlabeldotted
1条回答
网友
1楼 · 发布于 2024-09-29 00:16:43

您可以使用^{}来代替,这将为您提供如下输出

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的答案中还列出了其他方法

相关问题 更多 >