[英]Display percentage labels in Seaborn displot
我希望使用 Seaborn displot 顯示每個子圖中的百分比。 使用下面,我 plot 在不同行中的Item
中的每個唯一值。 而 Num 中的每個唯一值占據 x 軸。 目前顯示了Label
中的值,但我也希望將百分比顯示為文本。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({
'Num' : [1,2,1,2,3,2,1,3,2,2,1,2,3,3,1,3],
'Label' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],
'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],
})
g = sns.displot(data = df,
x = 'Num',
row = 'Item',
hue = 'Label',
row_order = ['Up','Down','Left','Right'],
discrete = True,
multiple = 'fill',
aspect = 4,
height = 2,
)
for ax in g.axes.flat:
ax.xaxis.labelpad = 8
ax.yaxis.labelpad = 8
ax.tick_params(which = 'both', width = 0.8, labelsize = 8)
for p in g.axes.flat:
txt = str(p.get_height().round(2)) + '%'
txt_x = p.get_x()
txt_y = p.get_height()
g.ax.text(txt_x,txt_y,txt)
PercentFormatter
以百分比格式標記 y 軸。 要訪問帶有各個條的補丁,您需要遍歷每個斧頭的補丁。 每個條有一個 xy position,一個高度和一個寬度。 高度表示百分比。 可以使用 x、y 以及寬度和高度的一半來計算條形的中心。
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter, MultipleLocator
import seaborn as sns
import pandas as pd
df = pd.DataFrame({
'Num': [1, 2, 1, 2, 3, 2, 1, 3, 2, 2, 1, 2, 3, 3, 1, 3],
'Label': ['A', 'B', 'C', 'B', 'B', 'C', 'C', 'B', 'B', 'A', 'C', 'A', 'B', 'A', 'C', 'A'],
'Item': ['Up', 'Left', 'Up', 'Left', 'Down', 'Right', 'Up', 'Down', 'Right', 'Down', 'Right', 'Up', 'Up', 'Right',
'Down', 'Left'],
})
g = sns.displot(data=df,
x='Num',
row='Item',
hue='Label',
row_order=['Up', 'Down', 'Left', 'Right'],
discrete=True,
multiple='fill',
aspect=4,
height=2,
)
for ax in g.axes.flat:
ax.xaxis.labelpad = 8
ax.yaxis.labelpad = 8
ax.tick_params(which='both', width=0.8, labelsize=8)
ax.xaxis.set_major_locator(MultipleLocator(1)) # x ticks at multiples of 1
ax.yaxis.set_major_formatter(PercentFormatter(1)) # percentage using 1 for 100%
ax.set_ylabel('Percentage')
for p in ax.patches:
h = p.get_height()
if h > 0: # skip empty bars
txt = f'{h * 100:.2f} %'
txt_x = p.get_x() + p.get_width() / 2
txt_y = p.get_y() + h / 2
ax.text(txt_x, txt_y, txt, ha='center', va='center')
plt.subplots_adjust(left=0.09) # make a bit more room for the label
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.