【问题标题】:For to configure matplotlib subplots within a for loopFor 在 for 循环中配置 matplotlib 子图
【发布时间】:2018-07-25 04:20:29
【问题描述】:

我正在尝试遍历 Pandas 数据框中的一些数据并绘制到不同的子图中,但不太确定我做错了什么。

代码如下:

df2 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True)
for i, col in enumerate(df2.columns):
    print(col)
    axes[i] = df2[col].plot(kind="box")

如何填满其他子图?

【问题讨论】:

  • df2[col].plot(kind="box", ax = axes[I])?

标签: python pandas matplotlib subplot


【解决方案1】:

有一种更简单的方法可以做到这一点,您只需使用选项 subplots=True 执行 df.plot,然后在此处更改异常值,垂直 (layout=(4,1)):

df2.plot(kind='box',subplots=True, layout=(4,1), figsize=(8,8))
plt.show()

或者,如果您更喜欢水平分布的子图 (layout=(1,4)):

df2.plot(kind='box',subplots=True, layout=(1,4),figsize=(15,8))
plt.show()

最后,您可以通过以下方式将所有箱线图放在一起:

df2.plot(kind='box', figsize=(8,8))
plt.show()

有关如何使用 pandas 进行可视化的更多信息,请查看documentation

【讨论】:

    【解决方案2】:

    您需要将轴作为参数传递给绘图函数。大致如下:

    df2 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
    fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True)
    for i, col in enumerate(df2.columns):
        print(col)
        df2[col].plot(kind="box", ax=axes[i])
    

    在您的示例中,您正在重新定义“轴”的元素。相反,您定义轴一次,然后告诉绘图函数要使用哪个轴进行绘图。

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 2020-02-09
      • 2021-06-10
      • 1970-01-01
      • 2016-06-17
      • 2021-08-02
      • 2016-03-16
      • 2022-07-07
      相关资源
      最近更新 更多