Python 熊猫:传递的轴数与要打印的列数不匹配
我想将熊猫数据帧的三列绘制为2x2子地块布局:Python 熊猫:传递的轴数与要打印的列数不匹配,python,pandas,matplotlib,Python,Pandas,Matplotlib,我想将熊猫数据帧的三列绘制为2x2子地块布局: 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) 出现以下
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)
出现以下错误:
ValueError: The number of passed axes must be 3, the same as the output plot
有没有解决这个问题的方法,而不必重新安排子地块的布局?如果
ax=df.plot(subplots=True,layout=(2,2))
ax
是一个包含4个元素的2x2阵列。这是4个轴,如果df
仅包含3列,则最后一个轴不可见。再次打印3列时,需要提供3个轴,而不是全部4个轴。一个选项是将ax
数组索引到要使用的列数
df2.plot(subplots=True,ax=ax.flatten()[:3])
完整示例:
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()