gpt4 book ai didi

python - 带有单个子图的 Matplotlib

转载 作者:行者123 更新时间:2023-12-04 00:56:45 24 4
gpt4 key购买 nike

我正在子图中绘制 Pandas 数据框的列。要绘制的列存储在数组 an 中。如果 len(an)>1,则下面的代码可以正常工作,即如果我绘制多个图形,

    fig, axs = plt.subplots(len(an))
for index, item in enumerate(an, start=0):
gd.plot(ax=axs[index],x="Date",y=item)

但它失败并出现错误

TypeError: 'AxesSubplot' object is not subscriptable

如果 len(an)==1

如果只有一个情节要绘制,是否可以让子情节发挥作用,或者我是否必须使用 if 单独处理这种情况?

最佳答案

根据matplotlib的文档,参数“squeeze”解决了你的问题:

squeeze: bool, optional, default: True

  • If True, extra dimensions are squeezed out from the returned array of Axes:
    • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
    • for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.
    • for NxM, subplots with N>1 and M>1 are returned as a 2D array.
  • If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

所以你的问题的解决方案是:

fig, axs = plt.subplots(1,len(an),squeeze=False)
for index, item in enumerate(an, start=0):
gd.plot(ax=axs[0,index],x="Date",y=item)

关于python - 带有单个子图的 Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61838540/

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