katzenjammer
katzenjammer

Reputation: 205

Pandas: Number of passed axes does not match the number of columns to plot

I want to plot three columns of a pandas data frame to a 2x2 subplot layout:

rand=np.random.random((12,6))
df=pd.DataFrame(columns=['a','b','c','d','e','f'],data=rand)
ax=df.loc[:,'a':'c'].plot(subplots=True,layout=(2,2))

This gives me the desired result (with an empty plot in the lower right corner). However, if I try to add another column to all of these subplots using

df.loc[:,'d':'f'].plot(subplots=True,ax=ax)

the following error occurs:

ValueError: The number of passed axes must be 3, the same as the output plot

Is there any solution to this problem without having to rearrange the layout of the subplots?

Upvotes: 3

Views: 3465

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339092

In case of

ax=df.plot(subplots=True,layout=(2,2))

ax is a 2x2 array with 4 elements. Those are the 4 axes, where the last one is invisible if df only contains 3 columns. When plotting again 3 columns you need to supply 3 axes, not all 4. An option is to index the ax array to the number of columns to use.

df2.plot(subplots=True,ax=ax.flatten()[:3])

Complete example:

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

rand=np.random.random((12,6))
df=pd.DataFrame(columns=['a','b','c','d','e','f'],data=rand)

ax=df.loc[:,'a':'c'].plot(subplots=True,layout=(2,2))
df.loc[:,'d':'f'].plot(subplots=True,ax=ax.flatten()[:3])

plt.show()

Upvotes: 6

Related Questions