[英]pandas histogram with logarithmic axes
我有一個帶有時間長度數據的pandas DataFrame,以秒為單位。 長度從幾秒到幾個月不等,因此在記錄后采用直方圖很方便,因為它更好地覆蓋了范圍。 這是一個示例代碼
%matplotlib inline
import numpy as np
import pandas as pd
x=np.random.lognormal(mean=10, sigma=1, size=10000)
df=pd.DataFrame(x, range(10000), columns=['timeLength'])
np.log10(df.timeLength).hist()
但是,x軸上的標簽是按比例縮放的。 有沒有辦法把它們作為10 ^ 1等等。 或者甚至更好,如果我可以把它們放在1秒,10秒,1分鍾,10分鍾,1小時,1天等等。
而不是記錄值,
np.log10(df.timeLength)
嘗試在計算直方圖時創建非均勻分箱。 這可以通過np.histogram
的bins
參數來完成。
基於
如果我可以把它們放在1秒,10秒,1分鍾,10分鍾,1小時,1天等等。
可以創建以下bin數組
# Bin locations (time in seconds)
bins = np.array([0, 1, 10, 60, 60*10, 60*60, 24*60*60])
原始數據集被放大以填充更多的箱( mean=5, sigma=2
而不是mean=10, sigma=1
),這僅是示例。 定義非均勻區間,計算直方圖並繪制圖。 箱子例如可以改變。
# Create random data in DataFrame
x = np.random.lognormal(mean=5, sigma=2, size=10000)
df = pd.DataFrame(x, columns=['timeLength'])
print df.describe()
print
# Create non-uniform bins. Unit in seconds.
bins = np.array([0, 1, 10, 60, 60*10, 60*60, 24*60*60])
print 'hisogram bins:', bins
# Get histogram of random data
y, x = np.histogram(df, bins=bins, normed=True)
# Correct bin placement
x = x[1:]
# Turn into pandas Series
hist = pd.Series(y, x)
# Plot
ax = hist.plot(kind='bar', width=1, alpha=0.5, align='center')
ax.set_title('Non-Uniform Bin Histogram')
ax.set_xlabel('Time Length')
ax.set_xticklabels(['1 s', '10 s', '1 Min', '1 Hr', '1 Day', '>1 Day'], rotation='horizontal')
timeLength
count 10000.000000
mean 1014.865417
std 4751.820312
min 0.062893
25% 36.941388
50% 144.081235
75% 556.223797
max 237838.467337
hisogram bins: [ 0 1 10 60 600 3600 86400]
如果這不是預期的結果,請告知。
如果要使用自定義分檔,可能需要將pd.cut
與.groupby().count()
使用並使用bar
:
x=np.random.lognormal(mean=10, sigma=1, size=10000)
df=pd.DataFrame(x, range(10000), columns=['timeLength'])
df['bin'] = pd.cut(df.timeLength,include_lowest=True, bins=[0, 1, 10, 60, 60**2, 60**2*24, df.timeLength.max()], labels=['1s', '10s', '1min', '1hr', '1d', '>1d'])
df.groupby('bin').count().plot.bar()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.