matplotlib secondary axes that spans half of the first one
-
01-03-2021 - |
Pregunta
I need a plot with two y axis but the second one should be half of the first one.
I was thinking on two different plot overlapped but I guess there is a simpler way.
Thank you very much.
Solución
You should check matplotlib gallery.
Maybe you are looking for something like this or this.
Then if you want ax2 (right axis) to span half of ax1 (left axis), get the y-limits of ax1:
(min_y, max_y) = ax1.get_ylim()
and set ax2 limits accordingly. For example:
ax2.set_ylim((min_y, max_y / 2.))
Edit:
After your comments, I worked a solution that probably fits better your needs. Here is the code modified from mpl gallery:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
(min_y, max_y) = ax2.get_ylim()
dist = (max_y - min_y) * 2.
ax2.set_ylim((min_y, max_y + dist))
yticklabels = ax2.get_yticklabels()
yticks = ax2.get_yticklines()
nlabels = len(yticklabels) / 2
nticks = len(yticks) / 2
for i in range(len(yticklabels)):
if i < nlabels:
yticklabels[i].set_color('r')
else:
yticklabels[i].set_visible(False)
for i in range(len(yticks)):
if i < nticks:
yticks[i].set_color('r')
else:
yticks[i].set_visible(False)
plt.show()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow