Story data with two Y axes (two blocks) in matplotlib

I am trying to build one time series, but I want to represent it in two units on the left and right axes. Here is what I have done so far.

fig, ax1 = plt.subplots() t = np.arange(1,50,1) s1 = np.sin(t)*20000+40000 #synthetic ts, but closer to my data ax1.plot(t, s1, 'b-') ax1.set_xlabel('time') ax1.set_ylim(20000,70000) ax1.set_ylabel('km3/year') km3yearToSv=31.6887646*(1/1e6) ax2 = ax1.twinx() s2 = s1*km3yearToSv ax2.plot(t, s2, 'b-') ax2.set_ylim(20000*km3yearToSv,70000*km3yearToSv) ax2.set_ylabel('Sv') 

enter image description here

By adjusting ylim (), I can make it look like one line, but you can see some alias. I would prefer that I do not have to apply data twice.

Any suggestions?

UPDATE: Thank you askewchan for the perfect solution!

+9
source share
2 answers

There is no need to apply it twice, this should give you the desired result:

 ax2 = ax1.twinx() ax2.set_ylim(20000*km3yearToSv, 70000*km3yearToSv) ax2.set_ylabel('Sv') 

A more reliable way to do this is to first extract the limits of the chart (in case you change them and they will no longer be 20000 and 70000 , or you want the chart to automatically adjust the limits:

 ax2 = ax1.twinx() mn, mx = ax1.get_ylim() ax2.set_ylim(mn*km3yearToSv, mx*km3yearToSv) ax2.set_ylabel('Sv') 

one plot

In general, with some other minor changes:

 import numpy as np import matplotlib.pyplot as plt mean, amp = 40000, 20000 t = np.arange(50) s1 = np.sin(t)*amp + mean #synthetic ts, but closer to my data fig, ax1 = plt.subplots() ax1.plot(t, s1, 'b-') ax1.set_xlabel('time') mn, mx = ax1.set_ylim(mean-amp, mean+amp) ax1.set_ylabel('km$^3$/year') km3yearToSv = 31.6887646e-6 ax2 = ax1.twinx() ax2.set_ylim(mn*km3yearToSv, mx*km3yearToSv) ax2.set_ylabel('Sv') 
+8
source

one small error in the code above:

 mn, mx = ax2.get_ylim() 

should be:

 mn, mx = ax1.get_ylim() 

Scale a new secondary axis based on the original.

+1
source

All Articles