gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:26:34 29 4
gpt4 key购买 nike

脑袋疼

我有一些代码可以在一长列中生成 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')

我想将这些图中的每一个都放入我在上面注释掉的图中,但我所有的尝试都失败了。我尝试将 ax=i 放入 plot 命令中,我得到了 'numpy.ndarray' object has no attribute 'get_figure'。此外,当我缩小比例并在一张一张的图中使用一个图来执行此操作时,我的 x 和 y 比例尺都会出现问题。我觉得我离答案很近了,但我需要一点插入力。谢谢。

最佳答案

subplots 返回的坐标轴句柄根据请求的子图数量而变化:

  • 对于 (1x1) 你得到一个 handle ,
  • 对于 (n x 1 or 1 x n) 你得到一维句柄数组,
  • 对于 (m x n) 你会得到一个二维的句柄数组。

您的问题似乎是由第 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/...)

您还可以 reshape 返回的数组,使其呈线性(正如我在 this answer 中使用的那样):

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

如链接解决方案中所述,如果您可能有 1x1 子图(然后接收单个坐标轴句柄;axs = np.array(axs) 就足够了),则 axs 需要一些按摩。


在阅读了 docs 之后更仔细一点(oops),设置 squeeze=False 会强制 subplots 返回二维矩阵,而不管 ncols/nrows 的选择如何。 (挤压 默认为 True)。

如果你这样做,你可以迭代二维(如果它对你的数据来说是自然的),或者使用上述任何一种方法线性迭代你的数据并计算一个二维索引到 ax

关于python - 将 pandas DataFrame.plot 填充到 matplotlib 子图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21962508/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com