簡體   English   中英

Seaborn:distplot()具有相對頻率

[英]Seaborn: distplot() with relative frequency

我正在嘗試在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頻率圖

我無法弄清楚如何將輸出轉換為頻率而不是計數。 我已經嘗試了許多不同類型的圖形來獲得頻率輸出,但無濟於事。 我也遇到過這個問題似乎要求帶有頻率的計數圖 (但是有另一個功能。)我試過用它作為指南卻失敗了。 任何幫助將不勝感激。 我對這個軟件和Python也很新。

我的數據如下所示,可以下載: 樣本數據

有一個sns.displot參數允許從count轉換到頻率(或密度,如sns引用它)。 它通常是假的,所以你必須用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.

特別是作為初學者,盡量保持簡單。 你有一個數字列表

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計算直方圖,該numpy.histogram返回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之間的范圍內。

在此輸入圖像描述

完整代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM