pandasmatplotlibsubplotmultiple-axes

matplotlib pyplot - how to combine multiple y-axis and multiple plots


I need to plot a collection of different plots whis at least two different y-axis each.

I managed to solve each task singularly:

1st: A collection of different plots:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

a1 = np.random.randint(0,10,(6,2))
a2 = np.random.randint(0,10,(6,2)) * 10
df = pd.DataFrame(np.hstack([a1,a2]), columns = list('abcd'))

plt.subplot(1,2,1)
plt.plot(df.index,df.a,'-b')
plt.plot(df.index,df.c,'-g')

plt.subplot(1,2,2)
plt.plot(df.index,df.b,'-b')
plt.plot(df.index,df.d,'-g')

enter image description here

2nd: Plots whis at least two different y-axis:

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

ax.plot(df.index,df.a,'-b')
ax2.plot(df.index,df.c,'-g')

enter image description here

But all my attempts to combine this both things failed. Does anyone have a solution?


Solution

  • Set up two axes for each subplot.

    ax0 = plt.subplot(1,2,1)
    ax1 = ax0.twinx()
    ax2 = plt.subplot(1,2,2)
    ax3 = ax2.twinx()
    

    Full Code

    fig = plt.figure()
    fig.subplots_adjust(wspace=0.3)
    ax0 = plt.subplot(1,2,1)
    ax1 = ax0.twinx()
    ax0.plot(df.index,df.a,'-b')
    ax1.plot(df.index,df.c,'-g')
    
    ax2 = plt.subplot(1,2,2)
    ax3 = ax2.twinx()
    ax2.plot(df.index,df.b,'-b')
    ax3.plot(df.index,df.d,'-g')
    
    plt.show()
    

    enter image description here