Data 공부

[데이터 시각화] Python - Error bar plot 그리기 (significance level추가) 본문

Data 공부/데이터 시각화

[데이터 시각화] Python - Error bar plot 그리기 (significance level추가)

Junseokk 2023. 6. 16. 16:53

Error bar plot 그리기 (significance level추가)


예제 코드)

import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt

temp1 = np.random.normal(30,50,100) # temp data 1
temp2 = np.random.normal(70,80,100) # temp data 2

# 각 temp data의 평균
temp1_mean = temp1.mean()
temp2_mean = temp2.mean()

# 각 temp data의 표준오차
temp1_err = temp1.std() / np.sqrt(len(temp1))
temp2_err = temp2.std() / np.sqrt(len(temp2))

# temp data들의 p_value 계산
_, p_val = st.ttest_ind(temp1, temp2)

def p_value_annotation(p_value): # p_value 치환 함수
    if p_value <= 0.0001:
        star = "****"
    elif p_value <= 0.001:
        star = "***"
    elif p_value <= 0.01:
        star = "**"
    elif p_value <= 0.05:
        star = "*"
    else:
        star = "ns"
    return star

# barplot 그리기위한 x 좌표
x = [1, 2]

# plot size
plt.figure(figsize=(4,5))

# bar plot
plt.bar(x, [temp1_mean, temp2_mean], yerr=[temp1_err, temp2_err], capsize=15, color='#CCCCCC')

# significance level & annotation 그리기
y, h, coll = max(temp1_mean, temp2_mean) + max(temp1_mean, temp2_mean)/5 , max(temp1_mean, temp2_mean)/50, 'k'
plt.plot([x[0], x[0], x[1], x[1]], [y, y+h, y+h, y], lw=1.5, c=coll)
plt.text((x[0]+x[1])*.5, y+h, p_value_annotation(p_val), ha='center', va='bottom', color=coll, fontsize=15)

plt.ylim(plt.gca().get_ylim()[0], plt.ylim(plt.gca().get_ylim())[1]+ plt.ylim(plt.gca().get_ylim())[1]*0.1) # y limit 설정
plt.xticks(x, ['temp1', 'temp2']) # x tick 설정
plt.gca().spines['right'].set_visible(False) # 축제거
plt.gca().spines['top'].set_visible(False) # 축제거
plt.show()

 

예제 PLOT)

<Error bar Plot>

 

반응형
Comments