Python:使用for loop创建matplotlib子图

发布于 2025-02-13 20:16:35 字数 1048 浏览 2 评论 0原文

我想知道如何通过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()

I would like to know how can I make my code more efficient with a for loop. I'm interested in making multiple subplots. In this example I'm using 4 but in reality I have 14.

So far, I've been copying/pasting the same block of code

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2025-02-20 20:16:35

您可以将轴和条件存储在列表中,并在它们上迭代以创建图。像这样的事情可以完成这项工作:

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"]
categories = sorted(list(df["category"].unique()))
fig, axes = plt.subplots(2, 2, figsize=(12, 12), dpi=100)
axes = list(chain.from_iterable(axes))

fig.suptitle('Distributions per category 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()

You could store the axes and conditions within lists and iterate over them to create your plots. Something like this would do the job:

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"]
categories = sorted(list(df["category"].unique()))
fig, axes = plt.subplots(2, 2, figsize=(12, 12), dpi=100)
axes = list(chain.from_iterable(axes))

fig.suptitle('Distributions per category 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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文