# Multiple overlapping plots with independent scaling in Matplotlib

### Question

I currently have code that calls `matplotlib.pylab.plot` multiple times to display multiple sets of data on the same screen, and Matplotlib scales each to the global min and max, considering all plots. Is there a way to ask it to scale each plot independently, to the min and max of that particular plot?

1
9
3/15/2009 7:28:34 AM

There's no direct support for this, but here's some code from a mailing list posting that illlustrates two independent vertical axes:

``````x=arange(10)
y1=sin(x)
y2=10*cos(x)

rect=[0.1,0.1,0.8,0.8]
a1=axes(rect)
a1.yaxis.tick_left()
plot(x,y1)
ylabel('axis 1')
xlabel('x')

a2=axes(rect,frameon=False)
a2.yaxis.tick_right()
plot(x,y2)
a2.yaxis.set_label_position('right')
ylabel('axis 2')
a2.set_xticks([])
``````
3
3/15/2009 12:14:35 PM

Here is a solution using date plots, and I think its the most optimized solution using twinx() a short hand for adding a second y axis.

``````import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime
import numpy
numpy.random.seed(0)
t = md.drange(datetime.datetime(2012, 11, 1),
datetime.datetime(2014, 4, 01),
datetime.timedelta(hours=1))  # takes start, end, delta
x1 = numpy.cumsum(numpy.random.random(len(t)) - 0.5) * 40000
x2 = numpy.cumsum(numpy.random.random(len(t)) - 0.5) * 0.002
fig = plt.figure()
fig.suptitle('a title', fontsize=14)
fig.autofmt_xdate()
plt.ylabel('axis 1')
plt.xlabel('dates')
ax2 = ax1.twinx()
ax1.plot_date(t, x1, 'b-', alpha=.65)
ax2.plot_date(t, x2, 'r-', alpha=.65)
plt.ylabel('axis 2')
plt.show()
``````

From the docs, matplotlib.pyplot.twinx(ax=None) Make a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None). The ticks for ax2 will be placed on the right, and the ax2 instance is returned. More here.