0
votes

I have some data that I would like to plot on one figure directly on top of each other. One set has a different y range. It seem I can either plot two sets with the same y-range using plt, or two sets with different ranges using ax2 = ax1.twinx(), but not all three. Is there some sneaky way of doing it?

Edit:

Apparently it's not as easy as it seemed from the answer!

def plot_data2(a = 0 , b = 0, c = 0 ):
  fig, ax1 = plt.subplots(figsize = (18,8))
  ax2 = ax1.twinx()
  ax1.plot(a, 'b')
  ax1.plot(b, 'g')
  ax2.plot(c, 'r')

  fig.tight_layout()
  plt.show()

plot_data(a=data1, b=data2)

enter image description here

So while I can now print three graphs together just fine. I'd like to be able to also choose to only print any two.

I was going to ask why the axes weren't scaled, but now as I'm typing it, I realize that it's because I assigned the default to 0, so it stretches the graph. Is there any way to only print two graphs and have them both scaled to fit? As well as update the axes labels accordingly. I guess I could write a couple if's inside the function, but I was hoping there was a more elegant way.

Oh, and one more thing! How about BOTH x and y ranges different?

1
Might be useful: https://matplotlib.org/gallery/ticks_and_spines/multiple_yaxis_with_spines.html - DEEPAK SURANA

1 Answers

0
votes

The following code:

import matplotlib.pyplot as plt

X = [1,2,3,4,5]

data = [
    [(6-x)  for x in X],        # Decreasing
    [3      for x in X],        # Horizontal
    [(10*x) for x in X]         # Increasing
]

print(data)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

ax1.plot(X, data[0])
ax1.plot(X, data[1])
ax2.plot(X, data[2], 'r')       # This is the dataset with a different y range
                                # Specify a color otherwise you'll get duplicated colors
plt.show()

Produces:

enter image description here

Where blue = data[0], orange = data[1], red = data[2] (on a different y axis).