【问题标题】:Python: Create matplotlib subplots using a for loopPython:使用 for 循环创建 matplotlib 子图
【发布时间】:2022-07-07 23:23:56
【问题描述】:

我想知道如何使用 for 循环使我的代码更高效。我有兴趣制作多个子图。在此示例中,我使用 4,但实际上我有 14。

到目前为止,我一直在复制/粘贴相同的代码块

df_A = df.loc[df['category'] == 'A'].copy()
df_B = df.loc[df['category'] == 'B'].copy()
df_C = df.loc[df['category'] == 'C'].copy()
df_D = df.loc[df['category'] == 'D'].copy()

dataframes = [df_A, df_B, df_C, df_D]

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 12), dpi=100)

fig.suptitle('Distributions per category in minutes', fontweight="bold", fontsize=15)

# category A
ax1.hist(df_A['time_spent'], color="darkcyan", edgecolor='black', bins=20)
ax1.set_title('Category A', fontsize=10)

# category B
ax2.hist(df_B['time_spent'], color="darkcyan", edgecolor='black', bins=20)
ax2.set_title('Category B', fontsize=10)

# category C
ax3.hist(df_C['time_spent'], color="darkcyan", edgecolor='black', bins=20)
ax3.set_title('Category C', fontsize=10)

# category D
ax4.hist(df_D['time_spent'], color="darkcyan", edgecolor='black', bins=20)
ax4.set_title('Category D', fontsize=10)

fig.tight_layout()
plt.show()

【问题讨论】:

    标签: python pandas for-loop matplotlib subplot


    【解决方案1】:

    您可以将坐标轴和条件存储在列表中并对其进行迭代以创建您的绘图。像这样的东西可以完成这项工作:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from itertools import chain
    
    df = pd.DataFrame(
        {
            "category": ["A", "B", "C", "D"] * 1000,
            "time_spent": np.random.rand(4000)
        }
    )
    
    categories = ["A", "B", "C", "D"]
    fig, axes = plt.subplots(2, 2, figsize=(12, 12), dpi=100)
    axes = list(chain.from_iterable(axes))
    
    fig.suptitle('Distributions per theme in minutes', fontweight="bold", fontsize=15)
    for i in range(len(axes)):
      axes[i].hist(df.loc[df['category'] == categories[i], 'time_spent'], color="darkcyan", edgecolor='black', bins=20)
      axes[i].set_title(f'Category {categories[i]}', fontsize=10)
      
    fig.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-23
      • 2021-08-02
      • 2015-06-22
      • 2013-09-24
      • 2015-08-18
      • 2021-01-06
      • 1970-01-01
      • 2018-07-25
      相关资源
      最近更新 更多