★distplot , histplot , twinx(), ticker , axvline()★정규분포 그래프★기초통계학-[Chapter03 - 05]
2022. 12. 6. 16:16
728x90
반응형
1. A 데이터프레임 생성
A='30.74 28.44 30.20 32.67 33.29 31.06 30.08 30.62 27.31 27.88 ' \
'26.03 29.93 31.63 28.13 30.62 27.80 28.69 28.14 31.62 30.61 ' \
'27.95 31.62 29.37 30.61 31.80 29.32 29.92 31.97 30.39 29.14 ' \
'30.14 31.54 31.03 28.52 28.00 28.46 30.38 30.64 29.51 31.04 ' \
'27.00 30.15 29.13 27.63 30.87 28.67 27.39 33.20 29.52 30.86 ' \
'34.01 29.41 31.18 34.59 33.35 33.73 28.39 26.82 29.53 32.55 ' \
'30.34 32.44 27.09 29.51 31.36 31.61 31.24 28.83 31.88 32.24 ' \
'31.72 28.34 29.89 30.27 31.42 29.11 29.36 32.24 29.56 31.72 ' \
'30.67 28.85 30.87 27.17 30.85 28.75 25.84 28.79 31.74 34.59 ' \
'32.69 26.23 28.20 31.62 33.48 28.00 33.86 29.22 26.50 30.89'
A = list(map(float , A.split(' ')))
#A = A.(lambda x : round(x ,2))
A
[30.740, 28.440, 30.200, 32.670, 33.290, 31.060,30.080,30.620, ···················]
A = pd.DataFrame(A)
A
A.describe()
2. 계급값 & 도수 값 구하기
bins = np.arange(23.5, 37.5 + 0.5 , 0.5)
hist, bins = np.histogram(A, bins)
print('hist : {}'.format(hist))
print('bins : {}'.format(bins))
Steps=[]
for i in range(len(bins)-1):
Steps.append((bins[i+1] - (0.5/2)))
print(Steps)
DOSU = pd.DataFrame({'계급값' : Steps , '도수' : hist})
DOSU
hist : [ 0 0 0 0 1 2 2 5 4 9 7 8 8 8 12 7 12 3 3 4 2 1 2 0
0 0 0 0] ==> 도수값
bins : [23.5 24. 24.5 25. 25.5 26. 26.5 27. 27.5 28. 28.5 29. 29.5 30.
30.5 31. 31.5 32. 32.5 33. 33.5 34. 34.5 35. 35.5 36. 36.5 37.
37.5] ==> 계급간격
Steps : [23.75, 24.25, 24.75, 25.25, 25.75, 26.25, 26.75, 27.25, 27.75, 28.25, 28.75, 29.25, 29.75, 30.25, 30.75, 31.25, 31.75, 32.25, 32.75, 33.25, 33.75, 34.25, 34.75, 35.25, 35.75, 36.25, 36.75, 37.25]
==> 계급값_2 ==>계급간격의 절반값
2-1 . 히스토그램 (by matplotlib)
fig = plt.figure(figsize=(8,8))
fig.set_facecolor('white')
plt.hist(A, Steps , rwidth = 0.8 , alpha = 0.5)
plt.title('계급 간격 별 도수 막대그래프')
plt.xlabel('계급간격' , fontsize = 14 , labelpad= 14 ,rotation = 0)
plt.ylabel('도수' , fontsize = 14 , labelpad= 14 ,rotation = 0)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
2-2 . 히스토그램 (by Seaborn)_ x축간격 설정 ticker.MultipleLocator(0.5)
from matplotlib import ticker
fig = plt.figure(figsize=(15,15))
fig.set_facecolor('white')
ax= sns.histplot(A, kde=True) #정규분포 그래프 표시
ax.set_xlim([Steps[0] , Steps[-1]])
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) #x축 간격을 0.5로 설정
plt.show()
2-3 . 도수분포표를 막대그래프로 표현 (by Seaborn)
fig = plt.figure(figsize=(15,15))
fig.set_facecolor('white')
ax = sns.barplot(x= Steps , y =hist)
for i,txt in enumerate(list(hist)):
b = txt
#print(b)
if b == max(list(hist)):
ax.text(i, b+0.2, str(txt)+'개' , ha='center' , color = 'red' , fontweight = 'bold' , fontsize=15)
#어디 막대, 막대기의 위쪽에
else:
ax.text(i, b+0.2, str(txt)+'개' , ha='center' , color = 'dimgray' , fontsize=15 , fontweight = 'bold')
2-4 . 도수분포표를 히스토그램 & 정규분포 표현 (by Seaborn, distplot 사용!!)
fig , ax1 = plt.subplots(figsize= (15,8))
ax1 = sns.distplot(A['data'],bins = 28 , kde=False)
ax1.set_xlim([Steps[0] , Steps[-1]])
ax1.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) #x축 간격을 0.5로 설정
for p in ax1.patches:
#print(p)
ax1.text(x = p.get_x() + p.get_width()/2,
y = p.get_height() + len(A)*0.001,
s = 'X좌표 : \n{}\n {} {}'.format(round(p.get_x(),3),int(p.get_height()),'개'),
#s = f'{(p.get_height()/ len(A)) * 100: 1.1f}개',
ha = 'center')
ax1.set_ylabel('갯수' , fontsize = 14 , labelpad= 14 ,rotation = 0)
ax2 = ax1.twinx() #한 그래프에 두번째 plot 넣기
ax2 = sns.distplot(A['data'],bins = 28 , hist=False , kde=True)
ax2.set_xlim([Steps[0] , Steps[-1]])
ax2.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) #x축 간격을 0.5로 설정
ax2.axes.yaxis.set_visible(False) #y축 없애기
plt.show()
==> X좌표 변경은 불가능한거 같다.
ax1.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) #x축 간격을 0.5로 설정
ax1 = sns.distplot(A['data'],bins = 28 , kde=False)
==> kde = False 해야 옆 y축 밀도가 아닌 질량으로 변경된다.
2-5 히스토그램 & 정규분포 표현 (by Seaborn, distplot 사용!!)
fig , ax1 = plt.subplots(figsize= (15,8))
ax1 = sns.distplot(A['data'],bins = 28 , kde=False)
ax1.set_xlim([Steps[0] , Steps[-1]])
ax1.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) #x축 간격을 0.5로 설정
for p in ax1.patches:
#print(p)
ax1.text(x = p.get_x() + p.get_width()/2,
y = p.get_height() + len(A)*0.001,
s = 'X좌표 : \n{}\n {} {}'.format(round(p.get_x(),3),int(p.get_height()),'개'),
#s = f'{(p.get_height()/ len(A)) * 100: 1.1f}개',
ha = 'center')
ax1.set_ylabel('갯수' , fontsize = 14 , labelpad= 14 ,rotation = 0)
ax2 = ax1.twinx() #한 그래프에 두번째 plot 넣기
ax2 = sns.distplot(A['data'],bins = 28 , hist=False , kde=True, color='red')
ax2.set_xlim([Steps[0] , Steps[-1]]) #x축 시작 지점과 끝지점 표현
ax2.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) #x축 간격을 0.5로 설정
ax2.axes.yaxis.set_visible(False) #y축 없애기
x_s1 = float(A.mean() - A.std()*1)
x_s2 = float(A.mean() - A.std()*2)
x_s3 = float(A.mean() - A.std()*3)
x_plus_s1 = float(A.mean() + A.std())
x_plus_s2 = float(A.mean() + A.std()*2)
x_plus_s3 = float(A.mean() + A.std()*3)
# 수직선 표현하기
ax2.axvline(x= x_s1, ymin=0 , ymax=1 , color = 'red' , linestyle ='solid' , label ='{}'.format(2))
ax2.text(x_s1 , .19 , f'x-s : {round(x_s1,2)}',fontsize=13)
ax2.axvline(x= x_s2, ymin=0 , ymax=1 , color = 'blue' , linestyle ='solid' , label ='{}'.format(2))
ax2.text(x_s2 , .19 , f'x-2s : {round(x_s2,2)}',fontsize=13)
ax2.axvline(x= x_s3, ymin=0 , ymax=1 , color = 'purple' , linestyle ='solid' , label ='{}'.format(2))
ax2.text(x_s3 , .19 , f'x-3s : {round(x_s3,2)}',fontsize=13)
ax2.axvline(x= x_plus_s1, ymin=0 , ymax=1 , color = 'red' , linestyle ='solid' , label ='{}'.format(2))
ax2.text(x_plus_s1 , .19 , f'x+1s : {round(x_plus_s1,2)}',fontsize=13)
ax2.axvline(x= x_plus_s2, ymin=0 , ymax=1 , color = 'blue' , linestyle ='solid' , label ='{}'.format(2))
ax2.text(x_plus_s2 , .19 , f'x+2s : {round(x_plus_s2,2)}',fontsize=13)
ax2.axvline(x= x_plus_s3, ymin=0 , ymax=1 , color = 'purple' , linestyle ='solid' , label ='{}'.format(2))
ax2.text(x_plus_s3 , .19 , f'x+3s : {round(x_plus_s3,2)}',fontsize=13)
plt.show()
==> 평균 : 30.138
==> 표준편차 : s = 1.991
출처 : [쉽게 배우는 생활속의 통계학] [북스힐 , 이재원]
※혼자 공부 정리용
728x90
반응형
'기초통계 > 평균,표준편차,분산' 카테고리의 다른 글
insert() , index★그룹화 자료의 분산과 표준편차★기초통계학-[Chapter03 - 07] (0) | 2022.12.07 |
---|---|
경험적규칙★체비쇼프 정리★기초통계학-[Chapter03 - 06] (0) | 2022.12.06 |
★DDOF = 1★모/표본분산 , 모/표본표준편차★평균편차★기초통계학-[Chapter03 - 04] (0) | 2022.12.02 |
np.median★절사평균, 중위수★기초통계학-[Chapter03 - 03] (0) | 2022.12.02 |
★가중평균, 표본평균★기초통계학-[Chapter03 - 02] (1) | 2022.12.02 |