2017-04-08 14 views
1

파이썬 3에서이 밀도 플롯을 다시 만들려고합니다. math.stackexchange.com/questions/845424/the-expected-outcome-of-a - 랜덤 게임 - 중 - 체스동일한 플롯에 여러 밀도 곡선을 그려야합니다. 파이썬 3에서 서브 세트 카테고리에 가중치를 붙입니다.

End Goal: I need my density plot to look like this

파란색 곡선 아래 면적은을 결합, 빨강, 녹색, 보라색 곡선의 그것과 동일하기 때문에 다른 결과 (블랙 승리, 그리기, 및 흰색 승리)는 전체 (전체)의 하위 집합입니다.

어떻게 파이썬을 실현하고 그에 따라 플롯합니까? 여기

는 시뮬레이션

from matplotlib import pyplot as plt 
import seaborn as sns 

black = results_df.loc[results_df['outcome'] == 'Black'] 
white = results_df.loc[results_df['outcome'] == 'White'] 
draw = results_df.loc[results_df['outcome'] == 'Draw'] 
win = results_df.loc[results_df['outcome'] != 'Draw'] 

Total = len(results_df.index) 
Wins = len(win.index) 

PercentBlack = "Black Wins ≈ %s" %('{0:.2%}'.format(len(black.index)/Total)) 
PercentWhite = "White Wins ≈ %s" %('{0:.2%}'.format(len(white.index)/Total)) 
PercentDraw = "Draw ≈ %s" %('{0:.2%}'.format(len(draw.index)/Total)) 
AllTitle = 'Distribution of Moves by All Outcomes (nSample = %s)' %(workers) 

sns.distplot(results_df.moves, hist=False, label = "All") 
sns.distplot(black.moves, hist=False, label=PercentBlack) 
sns.distplot(white.moves, hist=False, label=PercentWhite) 
sns.distplot(draw.moves, hist=False, label=PercentDraw) 
plt.title(AllTitle) 
plt.ylabel('Density') 
plt.xlabel('Number of Moves') 
plt.legend() 
plt.show() 

을 pastebin.com/YDVMx2DL 후, 1000 results_df의 .CSV 파일 인 코드는 상기 정말 밀도 곡선 가중치를 생성 하는 방법을 알아 내야 가중치없이 농도 곡선을 생산 이에 따라뿐만 아니라 전설에 내 레이블을 보존 분포를 조정

density curves, no weights; help 나는 또한 주파수 히스토그램을 시도

, 높이를 정확하게하지만, 나는 오히려 "깨끗한"모양을 위해 서로 겹쳐서 4 개의 곡선을 유지하고 싶습니다 ... 나는이 주파수 플롯을 좋아하지 않지만, 이것은 현재 현재의 수정입니다. 뿐만 아니라 맞춤 범례 백분율 표시 보존으로 정확한 서브 가중치 4 개 밀도 곡선과 제 줄거리를 출력 누구 파이썬 3 코드를 작성할 수없는 경우

results_df.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = "All") 
draw.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = PercentDraw) 
white.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = PercentWhite) 
black.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = PercentBlack) 
plt.title(AllTitle) 
plt.ylabel('Frequency') 
plt.xlabel('Number of Moves') 
plt.legend() 
plt.show() 

, 즉 훨씬 이해 될 것이다.

일단 농도 곡선이 올바른 부분 집합으로 채워지면 의 파이썬 3 코드에 관심이 있습니다. 각 밀도 곡선의 최대 점 좌표는입니다. 반복.

감사합니다.

답변

1

주의해야합니다. 당신이 만든 음모가 맞습니다. 표시된 모든 곡선은 기본 분포의 확률 밀도 함수입니다.

갖고 싶은 플롯에서 "모두"라고 표시된 곡선 만 확률 밀도 함수입니다. 다른 곡선들은 그렇지 않습니다.

원하는 플롯에 표시된 것처럼 크기를 조정하려면 커널 밀도 추정치를 직접 계산해야합니다. 이것은 scipy.stats.gaussial_kde()을 사용하여 수행 할 수 있습니다.

원하는 플롯을 재현하려면 두 가지 옵션이 있습니다.

모든 관련 사례에 대해 kde를 계산하고 샘플 수로 스케일합니다.

enter image description here

import numpy as np; np.random.seed(0) 
import matplotlib.pyplot as plt 
import scipy.stats 

a = np.random.gumbel(80, 25, 1000).astype(int) 
b = np.random.gumbel(200, 46, 4000).astype(int) 

kdea = scipy.stats.gaussian_kde(a) 
kdeb = scipy.stats.gaussian_kde(b) 

both = np.hstack((a,b)) 
kdeboth = scipy.stats.gaussian_kde(both) 
grid = np.arange(500) 

#weighted kde curves 
wa = kdea(grid)*(len(a)/float(len(both))) 
wb = kdeb(grid)*(len(b)/float(len(both))) 

print "a.sum ", wa.sum() 
print "b.sum ", wb.sum() 
print "total.sum ", kdeb(grid).sum() 

fig, ax = plt.subplots() 
ax.plot(grid, wa, lw=1, label = "weighted a") 
ax.plot(grid, wb, lw=1, label = "weighted b") 
ax.plot(grid, kdeboth(grid), color="crimson", lw=2, label = "pdf") 

plt.legend() 
plt.show() 
모든 개인 경우에 대해 계산 KDE 합계를 얻기 위해 그들의 합계를 정규화.

import numpy as np; np.random.seed(0) 
import matplotlib.pyplot as plt 
import scipy.stats 

a = np.random.gumbel(80, 25, 1000).astype(int) 
b = np.random.gumbel(200, 46, 4000).astype(int) 

kdea = scipy.stats.gaussian_kde(a) 
kdeb = scipy.stats.gaussian_kde(b) 

grid = np.arange(500) 


#weighted kde curves 
wa = kdea(grid)*(len(a)/float(len(a)+len(b))) 
wb = kdeb(grid)*(len(b)/float(len(a)+len(b))) 

total = wa+wb 

fig, ax = plt.subplots(figsize=(5,3)) 
ax.plot(grid, wa, lw=1, label = "weighted a") 
ax.plot(grid, wb, lw=1, label = "weighted b") 
ax.plot(grid, total, color="crimson", lw=2, label = "pdf") 

plt.legend() 
plt.show() 

enter image description here