Daidalos 31 mai 2014

Pour créer une figure avec deux axes des ordonnées sous matplotib il existe la fonction twinx. Exemple (source):

#!/usr/bin/env python
"""

Demonstrate how to do two plots on the same axes with different left
right scales.

The trick is to use *2 different axes*.  Turn the axes rectangular
frame off on the 2nd axes to keep it from obscuring the first.
Manually set the tick locs and labels as desired.  You can use
separate matplotlib.ticker formatters and locators as desired since
the two axes are independent.

This is achieved in the following example by calling the Axes.twinx()
method, which performs this work. See the source of twinx() in
axes.py for an example of how to do it for different x scales. (Hint:
use the xaxis instance and call tick_bottom and tick_top in place of
tick_left and tick_right.)

The twinx and twiny methods are also exposed as pyplot functions.

"""

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
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')
for tl in ax2.get_yticklabels():
    tl.set_color('r')
plt.savefig('ShareAxes.png')    
plt.show()


"""
Show how to display two scales on the left and right y axis -- Fahrenheit and Celsius
"""

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()  # ax1 is the Fahrenheit scale
ax2 = ax1.twinx()          # ax2 is the Celsius scale

def Tc(Tf):
    return (5./9.)*(Tf-32)

def update_ax2(ax1):
   y1, y2 = ax1.get_ylim()
   ax2.set_ylim(Tc(y1), Tc(y2))
   ax2.figure.canvas.draw()

# automatically update ylim of ax2 when ylim of ax1 changes.
ax1.callbacks.connect("ylim_changed", update_ax2)
ax1.plot([78, 79, 79, 77])

ax1.set_title('Two scales: Fahrenheit and Celsius')
ax1.set_ylabel('Fahrenheit')
ax2.set_ylabel('Celsius')

plt.savefig('ShareAxes_02.png')   
plt.show()


### Recherches associées

Liens Site
api example code: two_scales.py Matplotlib Doc
api example code: fahrenheit_celsius_scales.py Matplotlib Doc
Plotting two graphs that share an x-axis in matplotlib stackoverflow
pylab_examples example code: shared_axis_demo.py stackoverflow
In matplotlib, how do you display an axis on both sides of the figure? stackoverflow
How to add a second x-axis in matplotlib stackoverflow