[英]Display percentage labels in Seaborn displot
I'm hoping to display the percentages in each subplot using Seaborn displot.我希望使用 Seaborn displot 显示每个子图中的百分比。 Using below, I plot each unique value in
Item
in different rows.使用下面,我 plot 在不同行中的
Item
中的每个唯一值。 While the each unique value in Num takes up the x-axis.而 Num 中的每个唯一值占据 x 轴。 The values from
Label
are currently displayed, but I'm also hoping to display the percentages as text.目前显示了
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)
The PercentFormatter
labels the y-axis in percentage format. PercentFormatter
以百分比格式标记 y 轴。 To get access to the patches with the individual bars, you need to loop through the patches of each ax.要访问带有各个条的补丁,您需要遍历每个斧头的补丁。 Each bar has a xy position, a height and a width.
每个条有一个 xy position,一个高度和一个宽度。 The height indicates the percentage.
高度表示百分比。 The center of the bar can be calculated using x, y and half the width and height.
可以使用 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.