Seaborn:使用相对频率的distplot()函数

5

我正在为一个研究项目尝试使用Seaborn制作一些直方图。我希望y轴是相对频率,x轴从-180到180运行。

这是我用于其中一个直方图的代码:

import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns

df = pd.read_csv('sample.csv', index_col=0)

x = df.Angle
sns.distplot(x, kde=False);

这将输出: seaborn 频率图 我无法弄清如何将输出转换为频率而不是计数。我尝试了许多不同类型的图表来获得频率输出,但一无所获。我也看到了这个问题,它似乎在countplot with frequencies(但使用另一个函数)的要求。我尝试使用它作为指南,但失败了。任何帮助将不胜感激。我非常新手,对这个软件和Python也不熟悉。
我的数据看起来像下面这样,可以下载: 样本数据

一点数据会非常有帮助来回答问题。 - Bharath M Shetty
为回答者提供复制粘贴格式的数据是非常有帮助的。例如 df = pd.DataFrame({'number': [1,2,3,4,5,6], 'angle': [-0.126, 1, 9, 72.3, -44.2489, 87.44]}) - 3novak
2个回答

11

有一个sns.displot参数可以将计数转换为频率(或者按照sns的说法,密度)。它通常为False,所以您需要将其设置为True才能启用。在您的情况下:

sns.distplot(x, kde=False, norm_hist=True)

如果您想让x轴从-180到180运行,只需使用:

plt.xlim(-180, 180)

根据Seaborn文档

norm_hist : bool, optional

If True, the histogram height shows a density rather than a count. This is implied if a KDE or fitted density is plotted.

4
这将绘制概率密度而不是频率密度。请参见https://math.stackexchange.com/a/2667263/11687。 - farhanhubble
1
请注意,新的 sns.histplot 有更多选项,其中包括 stat="probability" - JohanC
请注意,sns.distplot已被弃用,而JohanC提到的sns.histplot(x, stat="probability")不仅是一种替代方法,而且是建议采用的方法。 - seulberg1
如果您还希望条形图具有相同的总体大小(以查看相对而非绝对差异),您还可以设置common_norm=False - dopexxx

8

特别是作为初学者,尽量保持简单。你有一个数字列表

a = [-0.126,1,9,72.3,-44.2489,87.44]

你想创建一个直方图,为此需要定义一些区间。假设你想将-180到180的范围分成宽度为20的区间,

import numpy as np
bins = np.arange(-180,181,20)

你可以使用numpy.histogram计算直方图,它会返回每个区间内的计数。
hist, edges = np.histogram(a, bins)

相对频率是每个区间内事件数量与总事件数的比值。
freq = hist/float(hist.sum())

因此,数量freq是您想要绘制为条形图的相对频率。

import matplotlib.pyplot as plt
plt.bar(bins[:-1], freq, width=20, align="edge", ec="k" )

这导致了以下图表,您可以从中读出例如33%的值位于0到20的范围内。

enter image description here

完整代码:

import numpy as np
import matplotlib.pyplot as plt

a = [-0.126,1,9,72.3,-44.2489,87.44]

bins = np.arange(-180,181,20)

hist, edges = np.histogram(a, bins)
freq = hist/float(hist.sum())

plt.bar(bins[:-1],freq,width=20, align="edge", ec="k" )

plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接