在Python中绘制频率百分比的直方图

问题描述 投票:0回答:2

我有一个评级列表,我正在为其绘制直方图。左侧(y 轴)显示频率计数,有没有办法让它显示基于流量的百分比。

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.hist(item['ratings'], bins = 5)
ax.legend()
ax.set_title("Ratings Frequency")
ax.set_xlabel("Ratings")
ax.set_ylabel("frequency")
ax.axhline(y=0, linestyle='--', color='k')
python matplotlib graph
2个回答
0
投票

您可以使用 countplot 尝试使用seaborn库,它将使数据可视化变得非常容易

import seaborn as sns   
sns.countplot()

0
投票

由于 y 轴上的标签显示每个条形的频率,因此您可以通过将其除以数据点的数量来轻松计算百分比。

示例:

import matplotlib.pyplot as plt

data = [1,2,3,4,4,4,5,5,6,7,8,8,9]
fig, ax = plt.subplots()
ax.hist(data)

ax.set_title("Default histogram with frequency on the y-axis")

enter image description here

现在,让我们计算并显示百分比:

# get frequency values
labels = ax.get_yticks()
# calculage percentage
labels = labels / len(data)
# format to string
labels = [f"{l:.1%}" for l in labels]
# set labels
ax.set_yticklabels(labels)

ax.set_title("Histogram with percentage on the y-axis")

enter image description here

提示:使用 set_yticklabels 时您可能会收到警告,但在这种情况下您可以忽略它

© www.soinside.com 2019 - 2024. All rights reserved.