如何使用 for 循环和 zip 函数在 python 中绘制子图?

How do I use a for loop and the zip function to plot subplots in python?

我是 python 的新手,一直坚持使用 zip 函数绘制子图。非常感谢您的帮助!

我想在数据框中为我的营养素绘制条形图,我可以在其中区分有机和非有机。对于我数据框中的每个国家/地区,我都想要子图。这是我的数据框:

country organic nutrients values
US False carbohydrates 45
US True carbohydrates 41
DE False calcium 37
DE True calcium 31

我的情节应该是这样的:

因为我的数据框中有很多国家,所以我想给我们一个 for 循环和 zip 函数。但是当我实现这段代码时,我得到一个空的canvas:

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(30, 15))

for i, ax in zip(range(0, 5), axes.flatten()):

    # Filter data for each country
    country_df = df[df["country"] == i]

    # Populate subplots
    ax.bar(country_df["nutrients"], country_df["values"], hue="organic")

    # Add x/y labels
    ax.set_xlabel("nutrients")
    ax.set_ylabel("average value")

有人可以帮忙吗?谢谢!!

您的代码存在问题,当您尝试按国家/地区过滤时,您实际上是在按数字过滤(它永远不会匹配您的图表)。为了轻松创建您在图中显示的分组,我建议使用 seaborn。一个可能的解决方案是:

import seaborn as sns

countries = set(df['countries'])
# Calculate the number of subplots based on the number of countries
ncols = 3
nrows = math.ceil(len(countries) / ncols)
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(30, 15))

for country, ax in zip(countries, axes.flatten()):
    # Filter data for each country
    country_df = df[df["country"] == country]   # Select by country name

    # Populate subplots
    sns.barplot(data=country_df, x="nutrients", y="values", hue="organic", ax=ax)

    # Add x/y labels
    ax.set_xlabel("nutrients")
    ax.set_ylabel("average value")