我有一個資料框字典,我正在使用下面的代碼為字典中的每個資料框生成堆積條形圖。該代碼按預期列印每個堆疊的條形圖(每個圖表在筆記本中一個接一個并在另一個下方),但我希望它在一個圖形上列印每個圖表,例如 4 行 3 列。
for i, key in enumerate(d):
plt.rcParams["figure.figsize"] = (5,3)
d[key].plot(kind = 'barh', width= 0.85, stacked = True, color = ['limegreen','gold', 'orange', 'red'])
plt.legend(bbox_to_anchor = (1.05, 1.025), title = "Categories")
plt.xlabel('Cumulative Percent')
plt.gca().xaxis.set_major_formatter(mtick.PercentFormatter())
plt.ylabel('Data Stream')
plt.gca().invert_yaxis()
plt.title(f'{key}')
plt.show()
uj5u.com熱心網友回復:
使用子圖:
# sample data
df = pd.DataFrame(
{f"col_{i}": np.random.randint(0,100, 50) for i in range(12)}
)
fig, axs = plt.subplots(4, 3, figsize=(25,20))
all_axs = axs.ravel()
for i, c in enumerate(df.columns):
ax = df[c].plot(kind = 'barh',
width= 0.85,
stacked = True,
color = ['limegreen','gold', 'orange', 'red'],
ax=all_axs[i])
ax.legend(title = "Categories")
ax.set_xlabel("Cumulative Percent")
ax.set_ylabel("Data Stream")
ax.xaxis.set_major_formatter(mtick.PercentFormatter())
ax.invert_yaxis()
fig.tight_layout()
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/493677.html
標籤:Python for循环 matplotlib 数据可视化
上一篇:For回圈語法約定
