1

When I am executing the below code, I can see the Demo is printing at the top horizontally. The Demo2 prints inside the plot with dotted line. But I can't see theDemo1? Why Demo1 is not printing and why Demo is coming top horizontally?

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()
William Miller
  • 9,839
  • 3
  • 25
  • 46
Rasmi Ranjan Nayak
  • 11,510
  • 29
  • 82
  • 122

1 Answers1

1

You could use plt.figlegend() instead, which will give you output like this

enter image description here

Or call plt.legend() after each plot to add the legend to each subplot individually,

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

If that's not exactly what you want there are other methods outlined in the answers to this question

William Miller
  • 9,839
  • 3
  • 25
  • 46