在seaborn上添加双XTICK,包括标准化连接

2024-05-19 12:52:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用seaborn绘制一些countplots

ax = sns.countplot(y='mydata', data=df,order = myorder).

enter image description here

现在,我想在我的xlabel上同时显示计数(如现在所示),同时显示同一条的总分数(计数/所有计数之和) 这是否容易做到


Tags: dfdata绘制orderseabornax分数计数
1条回答
网友
1楼 · 发布于 2024-05-19 12:52:37

您可以使用FuncFormatter创建自定义标签。在这种情况下,您可以将计数除以总数,并将它们放在换行符之后

import numpy as np; np.random.seed(42)
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

p = np.random.randint(2,26,10)
s = pd.Series(np.random.choice(np.arange(40,50), size=400, p=p/p.sum()))

counts = s.value_counts(sort=False)
total = counts.sum()

ax = counts.plot.barh()
ax.set_xlabel("counts")

fmt = lambda x, pos: f"{x:g}\n{x/total*100:g}%"
ax.xaxis.set_major_formatter(FuncFormatter(fmt))
ax.figure.subplots_adjust(bottom=0.2)
plt.show()

enter image description here

相关问题 更多 >