将pandas DataFrame.plot填充到matplotlib子图中

Kev*_*son 12 python matplotlib pandas

我的脑袋疼

我有一些代码可以在一个长列中生成33个图形

#fig,axes = plt.subplots(nrows=11,ncols=3,figsize=(18,50))
accountList =  list(set(training.account))
for i in range(1,len(accountList)):
    training[training.account == accountList[i]].plot(kind='scatter',x='date_int',y='rate',title=accountList[i])
#axes[0].set_ylabel('Success Rate')
Run Code Online (Sandbox Code Playgroud)

我想把这些情节中的每一个都放到我上面评论过的图中,但我所有的尝试都失败了.我试着投入ax=i情节命令然后得到'numpy.ndarray' object has no attribute 'get_figure'.此外,当我缩小并用一个一个图中的单个绘图进行此操作时,我的x和y标度都会变为heck.我觉得我接近答案,但我需要一点点推动.谢谢.

Bon*_*fum 14

subplots返回的轴处理根据请求的子图数量而变化:

  • 对于(1x1)你得到一个句柄,
  • 对于(nx 1或1 xn),您将得到一个1d数组的句柄,
  • 对于(mxn),你得到一个2d的句柄数组.

您的问题似乎是由于从第2个到第3个案例(即1d到2d轴阵列)的界面变化.如果您事先不知道阵列形状是什么,则以下片段可以提供帮助.

我发现numpy unravel_index对于遍历轴有用,例如:

ncol = 3 # pick one dimension
nrow = (len(accountList)+ ncol-1) / ncol # make sure enough subplots
fig, ax = plt.subplots(nrows=nrow, ncols=ncol) # create the axes

for i in xrange(len(accountList)):   # go over a linear list of data
  ix = np.unravel_index(i, ax.shape) # compute an appropriate index (1d or 2d)

  accountList[i].plot( ..., ax=ax[ix])   # pandas method plot
  ax[ix].plot(...)   # or direct axis object method plot (/scatter/bar/...)
Run Code Online (Sandbox Code Playgroud)

您还可以重新整形返回的数组,使其成为线性的(正如我在本回答中所使用的那样):

for a in ax.reshape(-1):
    a.plot(...)
Run Code Online (Sandbox Code Playgroud)

如链接解决方案中所述,如果您可能有1x1子图(然后接收单轴手柄,axs = np.array(axs)足够),则需要进行一些按摩.


并且在更仔细地阅读文档(oops)之后,设置squeeze=Falsesubplots以返回2d矩阵,而不管ncols/nrows的选择.(squeeze默认为True).

如果这样做,您可以迭代两个维度(如果它对您的数据很自然),或者使用上述任一方法线性迭代数据并计算二维索引ax.