0

When using ax.<plot_function> for plotting objects on a figure. How can I "hold on" the plot and render multiple plots on the same plot?

For example:

f = plt.figure(figsize=(13,6))
ax = f.add_subplot(111)

ax.plot(x1,y1)
ax.plot(x2,y2)

ax.plot(xN,yN)

I have tried adding:

ax.hold(True)

before I start plotting, but it doesn't work. I think the problem is that they all share the same y-scale and I only see the plot with the largest range of values.

How can I plot multiple 1D arrays of different scales on the same plot? Is there any way to plot them with different Y-axis next to each other?

Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564
  • This might help http://stackoverflow.com/questions/17523095/multiple-matplotlib-plots-in-same-figure-in-to-pdf-python – Srivatsan Aug 25 '14 at 19:55
  • What happens with the code? The `hold` seems unnecessary; whatever you draw by using `ax.something` will be drawn onto that graph. So, your coude should get you three lines in the same axis instance ("same plot"). – DrV Aug 25 '14 at 19:58
  • Thanks @DrV It doesn't. I get everything on different plots (subsequent plots override the previous plots) – Amelio Vazquez-Reina Aug 25 '14 at 20:05
  • DrV is correct. Are the x and y values defined on similar ranges? Each plot will re-adjust the x- and y-limits (unless you specify them exactly) so the previous plot(s) may be so tiny that they are invisible. – Ajean Aug 25 '14 at 20:19

1 Answers1

2

There should be nothing wrong with the code in the question:

import matplotlib.pyplot as plt
import numpy as np

# some data
x1 = np.linspace(0, 10, 100)
x2 = np.linspace(1, 11, 100)
xN = np.linspace(4, 5, 100)
y1 = np.random.random(100)
y2 = 0.5 + np.random.random(100)
yN = 1 + np.random.random(100)![enter image description here][1]

# and then the code in the question
f = plt.figure(figsize=(13,6))
ax = f.add_subplot(111)

ax.plot(x1,y1)
ax.plot(x2,y2)

ax.plot(xN,yN) 

# save the figure
f.savefig("/tmp/test.png")

Creates:

enter image description here

which should be pretty much what is expected. So the problem is not in the code.

Are you running the commands in a shell? Which one? IPython?

One wild guess: All three plots are plot, but the data in the plots is exactly the same for all plots, and they overlap each other.

DrV
  • 22,637
  • 7
  • 60
  • 72
  • Thanks @DrV. I think you are right. I believe the problem is that they all have very different y-ranges and I am only seeing the one with the highest Y-range. Is there any way to plot them on the same scale in the plot but have **multiple Y-axes** (i.e. ticks and values) next to each other on the same plot? – Amelio Vazquez-Reina Aug 25 '14 at 20:31