Plotting on left and right axis using matplotlib and numpy

Posted by lane

Example of Plotting on Left and Right axis
Plotting two lines on independent y-axis is useful when trying to overlay data that is on dramatically different scales. The following example (left_right.py) shows how to do this with matplotlib and numpy in python. I am not sure how to force the y-ticks on the left and right to automatically line up. If anyone know, please leave a comment with how to do it.

from pylab import *
from numpy import *

N = 100

# Create some random data for plotting on left axis and for the right axis
yLeft  = random.randn(N) + linspace(-25,25,N)
yRight = linspace(-50,50,N)**2

# Create left axis plots
axL = subplot(1,1,1)
plot(yLeft, '.-b')
grid(True)
ylabel("Left Y-Axis Data")
xlabel("X-Axis Data")
title("Data Plotted on Left and Right Axis")

# Create right axis and plots.  It is the frameon=False that makes this
# plot transparent so that you can see the left axis plot that will be
# underneath it.  The sharex option causes them to share the x axis.
axR = subplot(1,1,1, sharex=axL, frameon=False)
axR.yaxis.tick_right()
axR.yaxis.set_label_position("right")
plot(yRight, '.-g')
ylabel("Right Y-Axis Data")

# save the figure
savefig("left_right.png", dpi=72)

Tags: , ,

2 Responses to “Plotting on left and right axis using matplotlib and numpy”

  1. Patrick Laub Says:

    This looks like exactly what I need, though example
    doesn’t work on python 2.6.5, numpy 1.3.0, matplotlib
    0.99.1.1

  2. David Verelst Says:

    Although old, I think it is a nice post. Some additions for matching the right axis y-ticks to the left one and control the precision of the labels. I guess it is kind of an ugly solution…would be interested to know a better way to control it.

    Note: I use import pylab as plt, rather than * as indicated in the original blog post

    put after “# Create left axis plots” block:

    yticks_left, ylabels_left = plt.yticks()
    # identify the number of ticks on the left y-axis
    nr_yticks_left = len(yticks_left)

    put after “# Create right axis and plots.” block:

    yticks_right, ylabels_right = plt.yticks()
    tickmin, tickmax = yticks_right[0], yticks_right[-1]
    tickloc_yleft = np.linspace(tickmin,tickmax, num=nr_yticks_left)
    ax2.yaxis.set_ticks(tickloc_yleft)
    # and set the precision nicely of the right tick labels
    ax2.yaxis.set_ticklabels(["%.2f" % val for val in tickloc_yleft]

Leave a Reply