2017-07-31 206 views
0

我有兩個數據幀,它們具有相同的格式,我已經在下面生成了直方圖,標記爲'df'和'df2'。我有第三個數據框叫做'df_merged',它是以行爲單位的數據框'df'和'df2'的組合。如何繪製其他兩個直方圖條總和的直方圖?

我想要第三個直方圖條顯示'df'和'df2'的總和。我還希望將'df'和'df2'直方圖歸一化爲組合的'df_merged'直方圖,以使'df'和'df2'直方圖位於合併後的直方圖內。這是可行的嗎?

我的圖現在看起來不正確,因爲從x軸開始200,'df2'高於組合不合適,因爲它是'df2'和'df'的總和。我相信這是因爲我用三個直方圖中的每個bin加權值的總數。這是可行的嗎?

import numpy as np 
import pandas as pd 
from pandas import DataFrame, Series 
import matplotlib.pyplot as plt 
from matplotlib.colors import LinearSegmentedColormap 

df = df[['Column1']] 
df2 = df2[['Column1']] 
df_merged = pd.concat([df, df2], ignore_index=True) 

df_weights = 100*np.ones_like(df.values)/float(len(df)) 
df2_weights = 100*np.ones_like(df2.values)/float(len(df2)) 
df_merged_weights = 100*np.ones_like(df_merged.values)/float(len(df_merged)) 

fig, ax = plt.subplots() 
ax.hist(df.values, bins=25, weights=df_weights, color='black', histtype='step', label='df') 
ax.hist(df2.values, bins=200, weights=df2_weights, color='green', histtype='step', label='df2') 
ax.hist(df_merged.values, bins=200,weights=df_merged_weights,color='red', histtype='step', label='Combined') 

ax.margins(0.05) 
ax.set_ylim(bottom=0) 
ax.set_xlim([0,1000]) 
p.legend(loc='upper right') 

enter image description here

回答

1

您需要通過串接數組的長度來衡量一切。此外,你應該保持一致的bin大小和直方圖範圍。

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
from pandas import DataFrame 

np.random.seed(0) 
df = DataFrame(np.random.normal(300, 100, 2000)) # Two normal distributions 
df2 = DataFrame(np.random.normal(700, 100, 1500)) 
df_merged = pd.concat([df, df2], ignore_index=True) 

# weights 
df_weights = np.ones_like(df.values)/len(df_merged) 
df2_weights = np.ones_like(df2.values)/len(df_merged) 
df_merged_weights = np.ones_like(df_merged.values)/len(df_merged) 

plt_range = (df_merged.values.min(), df_merged.values.max()) 
fig, ax = plt.subplots() 
ax.hist(df.values, bins=100, weights=df_weights, color='black', histtype='step', label='df', range=plt_range) 
ax.hist(df2.values, bins=100, weights=df2_weights, color='green', histtype='step', label='df2', range=plt_range) 
ax.hist(df_merged.values, bins=100, weights=df_merged_weights, color='red', histtype='step', label='Combined', range=plt_range) 

ax.margins(0.05) 
ax.set_ylim(bottom=0) 
ax.set_xlim([0, 1000]) 
plt.legend(loc='upper right') 
# plt.savefig('output.png') 

Output

參見matplotlib.axes.Axes.hist

權重:(N,)array_like或無,可選

權重的陣列,相同的形狀作爲x的。 x中的每個值只有 貢獻了其相對於箱數的相關權重(而不是 1)。

+0

我需要的權重,因爲我想所有酒吧的總和等於1,所以我加權每個箱的總數值。我如何將這個代碼合併到代碼中?當我對它進行加權時,直方圖仍然不正確,因爲'df2'仍然大於原始文章中的組合。 – user112947

+0

我明白了......我更新了答案。基本上,「組合」分佈的總和是1,而另外兩個分佈是其中的幾分之一。不知道這是你在找什麼? – Constructor

+0

非常感謝。這正是我正在尋找的。 – user112947