Tuesday, July 24, 2012

A second y-axis in matplotlib

Simple code to add a second y-axis in matplotlib:


from mpl_toolkits.axes_grid1 import host_subplot
import matplotlib.pyplot as plt
host = host_subplot(111)
par = host.twinx()
host.set_xlabel("Distance")
host.set_ylabel("Density")
par.set_ylabel("Temperature")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
par.set_ylim(0,4)
plt.show()

Adapted from twinx.py


Now, I'm trying to figure out how to keep the first Y axis as the basic one.  For example, if I grab the x,y coords of a button press (via  fig.canvas.mpl_connect('button_press_event', onclick), they will be for the second y axis, not the first.  I wonder how to fix this?

1 comment:

  1. As far as I can tell, the left axis is still used; I don't know how to make the parasite axes the values returned. I think that might be a 'deep' question (in the sense of 'you have to go a few objects deep to find out').

    def onclick(x): print x,x.__dict__
    fig=gcf()
    fig.canvas.mpl_connect('button_press_event', onclick)

    ReplyDelete