我是 python 新手,堅持使用 zip 函式繪制子圖。非常感謝您的幫助!
我想在資料框中為我的營養素繪制條形圖,我可以在其中區分有機和非有機。對于我的資料框中的每個國家,我都想要子圖。這是我的資料框:
| 國家 | 有機的 | 營養素 | 價值觀 |
|---|---|---|---|
| 我們 | 錯誤的 | 碳水化合物 | 45 |
| 我們 | 真的 | 碳水化合物 | 41 |
| 德 | 錯誤的 | 鈣 | 37 |
| 德 | 真的 | 鈣 | 31 |
這就是我的情節應該是這樣的:
由于我的資料框中有很多國家,我想給我們一個 for 回圈和 zip 函式。但是當我實作這段代碼時,我得到了一個空的畫布:
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")
有人可以幫忙嗎?謝謝!!
uj5u.com熱心網友回復:
您的代碼的問題是當您嘗試按國家/地區過濾時,但實際上您是按數字過濾(這永遠不會與您的圖匹配)。為了輕松創建圖中所示的分組,我建議使用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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427735.html
下一篇:嵌套串列中的資料清理和子集化
