将 Pandas DataFrame.plot 填充到 matplotlib 子图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21962508/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stuffing a pandas DataFrame.plot into a matplotlib subplot
提问by Kevin Thompson
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=iinto the plot command and I get '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. I feel like I'm close to the answer, but I need a little push. Thanks.
我想将每个图都放入我在上面评论过的图中,但我所有的尝试都失败了。我尝试放入ax=iplot 命令,我得到'numpy.ndarray' object has no attribute 'get_figure'. 此外,当我缩小比例并在一张一张的图中用一个图来做这件事时,我的 x 和 y 比例都变得很糟糕。我觉得我已经接近答案了,但我需要一点推动。谢谢。
回答by Bonlenfum
The axes handles that subplotsreturns vary according to the number of subplots requested:
subplots返回的轴句柄根据请求的子图数量而变化:
- for (1x1) you get a single handle,
- for (n x 1 or 1 x n) you get a 1d array of handles,
- for (m x n) you get a 2d array of handles.
- 对于 (1x1) 你得到一个手柄,
- 对于 (nx 1 or 1 xn) 你得到一个一维的句柄数组,
- 对于 (mxn) 你得到一个二维的句柄数组。
It appears that your problem arises from the change in interface from the 2nd to 3rd cases (i.e. 1d to 2d axis array). The following snippets can help if you don't know ahead of time what the array shape will be.
看来您的问题是由于界面从第 2 种情况到第 3 种情况(即 1d 到 2d 轴阵列)的变化引起的。如果您事先不知道数组形状是什么,以下代码片段会有所帮助。
I have found numpy's unravel_indexuseful for iterating over the axes, e.g.:
我发现 numpyunravel_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)就足够了),则 axs 需要进行一些按摩。  
And after reading the docsmore carefully (oops), setting squeeze=Falseforces subplotsto return a 2d matrix regardless of the choices of ncols/nrows. (squeezedefaults to True).  
在更仔细地阅读文档(哎呀)之后,无论 ncols/nrows 的选择如何,设置squeeze=False强制subplots返回 2d 矩阵。(squeeze默认为真)。  
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. 
如果你这样做,你可以迭代两个维度(如果你的数据很自然),或者使用上述任何一种方法来线性迭代你的数据并计算一个二维索引到ax.
回答by camdenl
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 (i.e. 1, 3, 8)
这样我们就可以在我们的图表中使用标题,也可以容纳缺失值的组(即 1、3、8)

