18

In matplolib for a time line diagram can I set to y-axis different values on the left and make another y-axis to the right with other scale?

I am using this:

import matplotlib.pyplot as plt 

plt.axis('normal')
plt.axvspan(76, 76, facecolor='g', alpha=1)
plt.plot(ts, 'b',linewidth=1.5)
plt.ylabel("name",fontsize=14,color='blue')
plt.ylim(ymax=100)
plt.xlim(xmax=100)
plt.grid(True)
plt.title("name", fontsize=20,color='black')
plt.xlabel('xlabel', fontsize=14, color='b')
plt.show()

Can I give 2 y-axis in this plot?

In span selector:

 plt.axvspan(76, 76, facecolor='g', alpha=1)

I want to right text to characterize this span for example 'This is span selector' how can I make it?

Helen Firs
  • 353
  • 2
  • 4
  • 9

1 Answers1

27

You want twinx example. The gist if it is:

ax = plt.gca()
ax2 = ax.twinx()

You can then plot to the first axes with

ax.plot(...)

and the second with

ax2.plot(...)

In your case (I think) you want:

import matplotlib.pyplot as plt 

ax = plt.gca()
ax2 = ax.twinx()
plt.axis('normal')
ax2.axvspan(74, 76, facecolor='g', alpha=1)
ax.plot(range(50), 'b',linewidth=1.5)
ax.set_ylabel("name",fontsize=14,color='blue')
ax2.set_ylabel("name2",fontsize=14,color='blue')
ax.set_ylim(ymax=100)
ax.set_xlim(xmax=100)
ax.grid(True)
plt.title("name", fontsize=20,color='black')
ax.set_xlabel('xlabel', fontsize=14, color='b')
plt.show()
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • 3
    What do you do about legend? I had mine stacked on top of each other – raphael Apr 11 '17 at 19:19
  • 1
    @raphael Explicitly pass a position to the legend call to de-conflict them. I don't think the 'best' placement algorithm considers artists on other axes. – tacaswell Apr 11 '17 at 22:45
  • Suppose I have the x, y1 and y2 lists of values where y2 is a transformation of y1. Instead of doing plot(x, y1) and plot(x, y2) which would result in 2 different curves, I want to have one curve (for example from plot(x,y1) using y1 as the left y-axis scale and y2 as the right y-axis scale. Is that possible with `twinx`? – roschach Jun 13 '18 at 10:13
  • Having multiple legends is not an ideal solution, one should have to possibility to have one common legend. – Pieter Meiresone Apr 23 '21 at 08:29