我知道還有其他類似的條目,但沒有完全像這樣的條目。
假設我有這個資料框:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({"percentage": [0.3, 0.4, 0.5, 0.2],
"xaxis": ["set1", "set1", "set2", "set2"],
"hues": ["a", "b", "c", "d"],
"number": [1,2,3,4]
})
我在 Seaborn 中創建了一個分組條形圖:
sns.set(style="whitegrid")
fig, ax = plt.subplots(figsize=(10,10))
ax = sns.barplot(data=df,
x="xaxis",
y="percentage",
hue="hues")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)
for container in ax.containers:
ax.bar_label(container)
這很好地添加了“百分比”列中的標簽。
但
如何使用“數字”列中的條目標記條形圖?為了清楚起見,我選擇了數字 1、2、3、4 作為玩具示例。它們在我的真實資料中不是連續的。
作為參考,我使用的是 Python 3.9.X、Seaborn 0.11.2 和 Matplotlib 3.5.0。
我懷疑答案在容器中的某個地方,但不知道。
我還看到了使用此代碼的潛在答案:
for index, row in df.iterrows():
ax.text(insert_codehere)
但這似乎對我也不起作用。
提前致謝。

uj5u.com熱心網友回復:
for container, number in zip(ax.containers, df.number):
ax.bar_label(container, labels=[number, number])

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418150.html
標籤:
