Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: left yaxis and right yaxis to have different units

I'm plotting curves in Kelvin. I would like to have the left yaxis to show units in Kelvin and the right yaxis to show them in Celsius, and both rounded to the closest integer (so the ticks are not aligned, as TempK=TempC+273.15)

fig=plt.figure
figure=fig.add_subplot(111)
figure.plot(xpos, tos, color='blue')

I should not use twinx() as it allows superimposing curves with two different scales, which is not my case (only the right axis has to be changed, not the curves).

like image 860
Bruno von Paris Avatar asked Jun 25 '13 12:06

Bruno von Paris


People also ask

How do I change the axis units in Matplotlib?

To set the unit length of an axis in Matplotlib, we can use xlim or ylim with scale factor of the axes, i.e., of unit length times.

How do I merge two graphs with different axis in Matplotlib?

The way to make a plot with two different y-axis is to use two different axes objects with the help of twinx() function. We first create figure and axis objects and make a first plot. In this example, we plot year vs lifeExp. And we also set the x and y-axis labels by updating the axis object.


1 Answers

enter image description hereI found the following solution:

fig=plt.figure
figure=fig.add_subplot(111)
figure.plot(xpos, tos, color='blue')
... plot other curves if necessary
... and once all data are plot, one can create a new axis

y1, y2=figure.get_ylim()
x1, x2=figure.get_xlim()
ax2=figure.twinx()
ax2.set_ylim(y1-273.15, y2-273.15)
ax2.set_yticks( range(int(y1-273.15), int(y2-273.15), 2) )
ax2.set_ylabel('Celsius')
ax2.set_xlim(x1, x2)
figure.set_ylabel('Surface Temperature (K)')

Do not forget to set the twinx axis xaxis!

like image 161
Bruno von Paris Avatar answered Oct 13 '22 18:10

Bruno von Paris