How can I generate secondary y-axis on pandas subplots?

Viewed 119

I managed to get two sets of multiple plots for the (1) 'Temperature' and (2) 'Power demand' for 12 months across a specific year.

# Let's plot the temperature for each month of the year

dfp = temp_df.pivot_table(index='HR', columns='MO', values='T2M')
ax = dfp.plot(kind='line', subplots=True, figsize=(20, 30), layout=(6, 2), rot=90, legend=True)

enter image description here

# Let's plot the power demand for each month of the year

dfp = frame.pivot_table(index='Time', columns='Month', values='kWh')
ax = dfp.plot(kind='line', subplots=True, figsize=(20, 30), layout=(6, 2), rot=90, legend=True)

enter image description here

To compare the monthly trends, for each month, I would like to overlay the 'Temperature' and the 'Power demand' and create 12 subplots with multiple Y-axis. I've tried to generate a new axes instance, on the twin-X axes as below, but it didn't work.

dfp = frame.pivot_table(index='Time', columns='Month', values='kWh')
ax = dfp.plot(kind='line', subplots=True, figsize=(20, 30), layout=(6, 2), rot=90, legend=True)
ax2=ax.twinx()
dfp = temp_df.pivot_table(index='HR', columns='MO', values='T2M')
ax2 = dfp.plot(kind='line', subplots=True, figsize=(20, 30), layout=(6, 2), rot=90, legend=True)

# create figure and axis objects with subplots()
fig,ax = plt.subplots()
# make a plot
ax.plot(frame['Time'], frame['kWh'], color="red", marker="o")
# set x-axis label
ax.set_xlabel("Time",fontsize=14)
# set y-axis label
ax.set_ylabel("kWh",color="red",fontsize=14)

# twin object for two different y-axis on the sample plot
ax2=ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(temp_df['HR'], temp_df['T2M'],color="blue",marker="o")
ax2.set_ylabel("Temperature",color="blue",fontsize=14)
plt.show()

And the following error message comes up:

enter image description here

I did some research and it looks like the issue is due to how matplotlib handles subplots. Therefore maybe the twinx() method is not appropriate for this purpose. Do you know another way to generate subplots with multiple Y-axis?

1 Answers

The return value of dfp.plot(subplots=True, layout=(6, 2), ...) is not a single Axes object but a 6x2 array of Axes, so that's why twinx() can't be called on it. Note that Axes arrays are generally pluralized as axs instead of just ax for clarity.

To plot the temperatures onto a twinx() grid using another pandas subplots plot:

  • Create a secondary axs2 array by calling twinx() on each Axes of axs
  • Set ax=axs2 in the temperature plot
# plot kWh onto 6x2 axs grid
axs = (frame.pivot_table(index='Time', columns='Month', values='kWh')
            .plot(subplots=True, layout=(6, 2), figsize=(20, 30), rot=90, legend=True))

# create secondary y for all axs
axs2 = [ax.twinx() for ax in axs.ravel()]

# plot T2M onto secondary axs2 grid
(temp_df.pivot_table(index='HR', columns='MO', values='T2M')
        .plot(ax=axs2, subplots=True, layout=(6, 2), figsize=(20, 30), rot=90, legend=True))
Related