Amri Rasyidi
Amri Rasyidi

Reputation: 193

How to set same axis value on multiple subplots?

I have data of x and y

I want to create small multiple line chart of each line. I tried the code from this page. I modified several line to match my code. Here is my code:

fig, axs = plt.subplots(4, 5, figsize = (15,15))
ylim = (-100, 55)
k = 0
for i in range(4):
    for j in range(5):
        to_plot = real.loc[real['order_number'] == orderlist[k]]
        axs[i,j].plot(to_plot['event_timestamp'], to_plot['altitude_in_meters'])
        axs[i,j].plot(to_plot['event_timestamp'], to_plot['RASTERVALU'])
        k+=1

The orderlist is a list that contains the order number. I want to make every chart have same limit for y axis, but ylim = (-100,55) doesn't do the work, Instead I have this chart with different y axis.

small multiple

How can I make small multiple chart with same value of y axis on each charts ?

Upvotes: 3

Views: 1678

Answers (1)

William Miller
William Miller

Reputation: 10320

ylim = (-100, 55)

Does nothing on it’s own but create a tuple called ylim. What you need to do is call the matplotlib.axes.Axes.set_ylim method for each axes instance with ylim as an argument, I.e.

fig, axs = plt.subplots(4, 5, figsize = (15,15))
ylim = (-100, 55)
k = 0
for i in range(4):
    for j in range(5):
        to_plot = real.loc[real['order_number'] == orderlist[k]]
        axs[i,j].plot(to_plot['event_timestamp'], to_plot['altitude_in_meters'])
        axs[i,j].plot(to_plot['event_timestamp'], to_plot['RASTERVALU'])
        axs[i,j].set_ylim(ylim)
        k+=1

If you do not want the y-tick labels between plots drawn (since the y-axis will be the same for all plots) you can also do

fig, axs = plt.subplots(4, 5, sharey=True, figsize = (15,15))
axs[0,0].set_ylim([-100, 55])
k = 0
for i in range(4):
    for j in range(5):
        to_plot = real.loc[real['order_number'] == orderlist[k]]
        axs[i,j].plot(to_plot['event_timestamp'], to_plot['altitude_in_meters'])
        axs[i,j].plot(to_plot['event_timestamp'], to_plot['RASTERVALU'])
        k+=1

Upvotes: 2

Related Questions