如何解决在Seaborn CountPlot中注释组的百分比
以下代码获取所有碰撞的百分比。但是,我想获得组内的百分比。例如。中块(与交叉点无关)具有2个标签,即1(红色)或2(绿色/蓝色)。当前,这些条旁边的百分比是全部百分比(条数/所有碰撞),但是我只需要在一个y轴标签中显示该百分比。例如。对于中间街区(与路口无关),条数/中间街区内的所有碰撞(与路口无关)。我不知道该怎么做,所以如果有人可以向我指出正确的方向或给我一些我可以学习理解的代码,我将不胜感激。
非常感谢您抽出宝贵的时间。
plt.style.use('ggplot')
plt.figure(figsize = (20,15))
ax = sb.countplot(y = "JUNCTIONTYPE",hue = "SEVERITYCODE",data = dfm)
plt.title('Number of Persons vs. Number of Collisions by Severity',fontsize = 30)
plt.xlabel('Number of Collisions',fontsize = 24)
plt.ylabel('Number of Persons',fontsize = 24)
plt.tick_params(labelsize=18);
plt.legend(fontsize = 18,title = "Severity",loc = 'lower right')
plt.text(5,6,"figure 8: Number of persons plotted against the number of collisions grouped by severity",fontsize = 16)
# labels = [item.get_text() for item in ax.get_yticklabels()]
# labels[0] = 'No'
# labels[1] = 'Yes'
# ax.set_yticklabels(labels)
for p in ax.patches:
width = p.get_width()
height = p.get_height()
x,y = p.get_xy()
ax.annotate(int(width),((x + width),y),xytext = (30,-25),fontsize = 18,color = '#000000',textcoords = 'offset points',ha = 'right',va = 'center')
for p in ax.patches:
width = p.get_width()
height = p.get_height()
x,y = p.get_xy()
totals = []
for i in ax.patches:
totals.append(i.get_width())
total = sum(totals)
ax.text(width + 0.3,y + 0.38,str(
round((width/total) * 100,2))
+ '%',fontsize=18)
解决方法
您可以预先计算每个组的百分比,并使用seaborn / matplotlib
绘制条形的顺序来引用它们。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
titanic = sns.load_dataset('titanic')
# prepare the dataset
df = (titanic
.groupby(["embark_town","survived"])
.size()
.reset_index()
.replace({"survived": {0:"no",1:"yes"}})
.rename(columns={0:"count"}))
# calculate survival % per town of embarkation
df["percent"] = (df
.groupby("embark_town")
.apply(lambda x: x["count"] / x["count"].sum()).values)
# sort the dataframe to match the drawing order
df.sort_values(by=["survived","embark_town"],inplace=True)
# visualisation
plt.style.use('ggplot')
fig = sns.catplot(
x="count",y="embark_town",hue="survived",kind="bar",data=df,height=4,aspect=2)
for i,bar in enumerate(fig.ax.patches):
height = bar.get_height()
fig.ax.annotate(
# reference the pre-calculated row in the dataframe
f"{df.iloc[i,3] :.0%}",xycoords="data",xytext=(20,-15),textcoords="offset points",xy=(bar.get_width(),bar.get_y()),ha='center',va='center')
# make space for annonations
plt.margins(x=0.2)
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。