gpt4 book ai didi

python - 如何在分组条形顶部添加百分比

转载 作者:IT老高 更新时间:2023-10-28 22:25:07 26 4
gpt4 key购买 nike

鉴于以下计数图,我如何在条形顶部放置百分比?

import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", hue="who", data=titanic)

enter image description here

例如,对于“First”,我希望在各自的条形图上显示 First men/total First、First women/total First、First children/total First。

最佳答案

seaborn.catplot 组织函数返回一个 FacetGrid,它使您可以访问无花果、斧头及其补丁。如果在没有绘制任何其他内容的情况下添加标签,您就会知道哪些条形图来自哪些变​​量。从@LordZsolt 的回答中,我选择了 order 参数到 catplot:我喜欢明确说明,因为现在我们不依赖 barplot 函数使用我们认为的顺序默认。

import seaborn as sns
from itertools import product

titanic = sns.load_dataset("titanic")

class_order = ['First','Second','Third']
hue_order = ['child', 'man', 'woman']
bar_order = product(class_order, hue_order)

catp = sns.catplot(data=titanic, kind='count',
x='class', hue='who',
order = class_order,
hue_order = hue_order )

# As long as we haven't plotted anything else into this axis,
# we know the rectangles in it are our barplot bars
# and we know the order, so we can match up graphic and calculations:

spots = zip(catp.ax.patches, bar_order)
for spot in spots:
class_total = len(titanic[titanic['class']==spot[1][0]])
class_who_total = len(titanic[(titanic['class']==spot[1][0]) &
(titanic['who']==spot[1][1])])
height = spot[0].get_height()
catp.ax.text(spot[0].get_x(), height+3, '{:1.2f}'.format(class_who_total/class_total))

#checking the patch order, not for final:
#catp.ax.text(spot[0].get_x(), -3, spot[1][0][0]+spot[1][1][0])

生产

barplot of three-by-three variable values, with subset calculations as text labels

另一种方法是明确地进行汇总,例如使用优秀的 pandas,并使用 matplotlib 进行绘图,还可以自己进行样式设置。 (尽管即使使用 matplotlib 绘图功能,您也可以从 sns 上下文中获得相当多的样式。试试看——)

关于python - 如何在分组条形顶部添加百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31749448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com