【问题标题】:Seaborn: distplot() with relative frequencySeaborn:具有相对频率的 distplot()
【发布时间】:2018-02-11 13:39:31
【问题描述】:

我正在尝试在 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);

这输出:

我不知道如何将输出转换为频率而不是计数。我尝试了许多不同类型的图表来获得频率输出,但无济于事。我也遇到过这个问题,它似乎要求countplot with frequencies(但有另一个功能。)我试过用它作为指导,但失败了。任何帮助将不胜感激。我对这个软件和 Python 也很陌生。

我的数据如下所示,可以下载:

【问题讨论】:

  • 一点数据对回答很有帮助。
  • 回答者以复制粘贴格式提供数据很有帮助。类似df = pd.DataFrame({'number': [1,2,3,4,5,6], 'angle': [-0.126, 1, 9, 72.3, -44.2489, 87.44]})

标签: python pandas matplotlib data-visualization seaborn


【解决方案1】:

有一个sns.displot 参数允许从计数转换为频率(或密度,如 sns 所指)。它通常为 False,因此您必须使用 True 启用它。在你的情况下:

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

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

plt.xlim(-180,180)

来自Seaborn Docs

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.

【讨论】:

【解决方案2】:

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

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

您要为其创建直方图。为了定义直方图,您需要一些 bin。所以假设你想将 -180 到 180 之间的范围划分为宽度为 20 的 bin,

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

您可以使用 numpy.histogram 计算直方图,它会返回 bin 中的计数。

hist, edges = np.histogram(a, bins)

相对频率是每个bin中的数字除以事件总数,

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 之间。

完整代码:

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()

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2021-11-26
    • 2020-07-26
    • 1970-01-01
    • 2016-08-05
    • 2012-06-24
    • 2019-04-19
    • 2015-10-20
    相关资源
    最近更新 更多