user5576
user5576

Reputation: 129

Matplotlib several subplots and axes

I am trying to use matplotlib to plot several subplots, each with 2 y-axis (the values are completely different between the two curves, so I have to plot them in different y-axis)

To plot one graph with 2 y-axis I do:

fig, ax1 = plt.subplots(figsize=(16, 10))
ax2 = ax1.twinx()
ax1.plot(line1, 'r')
ax2.plot(line2, 'g')

To plot 2 subplots, one with each curve I do:

plt.subplot(2,1,1)
plt.plot(line1, 'r')
plt.subplot(2,1,2)
plt.plot(line2, 'g')

I can't manage to merge the two methods.

I wanted something like:

fig, ax1 = plt.subplots(figsize=(16, 10))
plt.subplot(2,1,1)
ax2 = ax1.twinx()
ax1.plot(line1, 'r')
ax2.plot(line2, 'g')
plt.subplot(2,1,2)
ax1.plot(line3, 'r')
ax2.plot(line4, 'g')

But this doesn't work, it just shows 2 empty subplots.

How can I do this?

Upvotes: 1

Views: 6156

Answers (1)

James
James

Reputation: 36608

You should create your subplots first, then twin the axes for each subplot. It is easier to use the methods contained in the axis object to do the plotting, rather than the high level plot function calls.

The axes returned by subplots is an array of axes. If you have only 1 column or 1 row, it is a 1-D array, but if both are greater than 1 it is a 2-D array. In the later case, you need to either .ravel() the axes array or iterate over the rows and then axes in each row.

import numpy as np
import matplotlib.pyplot as plt

# create a figure with 4 subplot axes
fig, axes = plt.subplots(2,2, figsize=(8,8))

for ax_row in axes:
    for ax in ax_row:
        # create a twin of the axis that shares the x-axis
        ax2 = ax.twinx()
        # plot some data on each axis.
        ax.plot(np.arange(50), np.random.randint(-10,10, size=50).cumsum())
        ax2.plot(np.arange(50), 100+np.random.randint(-100,100, size=50).cumsum(), 'r-')

plt.tight_layout()
plt.show()

enter image description here

Upvotes: 3

Related Questions