简体   繁体   English

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

[英]Stuffing a pandas DataFrame.plot into a matplotlib subplot

My brain hurts 我的脑袋疼

I have some code that produces 33 graphics in one long column 我有一些代码可以在一个长列中生成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')

I'd like to get each of those plots into the figure that I have commented out above, but all my attempts are failing. 我想把这些情节中的每一个都放到我上面评论过的图中,但我所有的尝试都失败了。 I tried putting ax=i into the plot command and I get 'numpy.ndarray' object has no attribute 'get_figure' . 我尝试将ax=i放入plot命令中,我得到'numpy.ndarray' object has no attribute 'get_figure' Also, when I scale back and do this with one single plot in a one by one figure, my x and y scales both go to heck. 此外,当我缩小并用一个一个图中的单个绘图进行此操作时,我的x和y标度都会变为heck。 I feel like I'm close to the answer, but I need a little push. 我觉得我接近答案,但我需要一点点推动。 Thanks. 谢谢。

The axes handles that subplots returns vary according to the number of subplots requested: 处理subplots返回的轴根据请求的子图数量而变化:

  • for (1x1) you get a single handle, 对于(1x1)你得到一个句柄,
  • for (nx 1 or 1 xn) you get a 1d array of handles, 对于(nx 1或1 xn),您将得到一个1d数组的句柄,
  • for (mxn) you get a 2d array of handles. for(mxn)你得到一个二维数组的句柄。

It appears that your problem arises from the change in interface from the 2nd to 3rd cases (ie 1d to 2d axis array). 看来您的问题是由于从第2个到第3个案例(即1d到2d轴阵列)的界面变化。 The following snippets can help if you don't know ahead of time what the array shape will be. 如果您事先不知道阵列形状是什么,则以下片段可以提供帮助。

I have found numpy's unravel_index useful for iterating over the axes, eg: 我发现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/...)

You can also reshape the returned array so that it is linear (as I used in this answer ): 您还可以重新整形返回的数组,使其呈线性(正如我在本答案中所使用的那样):

for a in ax.reshape(-1):
    a.plot(...)

As noted in the linked solution, axs needs a bit of massaging if you might have 1x1 subplots (and then receive a single axes handle; axs = np.array(axs) is enough). 如链接解决方案中所述,如果您可能有1x1子图(然后接收单轴手柄; axs = np.array(axs)就足够了),则需要进行一些按摩。


And after reading the docs more carefully (oops), setting squeeze=False forces subplots to return a 2d matrix regardless of the choices of ncols/nrows. 并且在仔细阅读文档 (oops)之后,设置squeeze=False迫使subplots返回2d矩阵,而不管ncols / nrows的选择。 ( squeeze defaults to True). squeeze默认值设为True)。

If you do this, you can either iterate over two dimensions (if it is natural for your data), or use either of the above approaches to iterate over your data linearly and computing a 2d index into ax . 如果这样做,您可以迭代两个维度(如果它对您的数据很自然),或者使用上述任一方法线性迭代数据并将2d索引计算为ax

Expanding on Bonlenfum's answer, here's a way to do it with a groupby clause: 扩展Bonlenfum的答案,这是使用groupby子句的方法:

accountList = training.account.unique()
accountList.sort()
for i, group in training.groupby('account'):
    ix = np.where(accountList==i)[0][0]
    ix = np.unravel_index(ix, ax.shape)
    group.plot(ax=ax[ix],title = i)

This way we can use the title in our graphs, and also accommodates groups with values that are missing (ie 1, 3, 8) 这样我们就可以在图表中使用标题,并且还可以容纳缺少值的组(即1,3,8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM