我想将 pandas 数据框的三列绘制成 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)
出现以下错误:
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()
