binned errorbar plot with matplotlib
                                            
                                                
                                                
                                                
                                                
                                                
                                                 10858 단어  errorbarbinningmatplotlib
                    
목적
왼쪽 그림과 같은 산점도를 그릴 수있는 상황에서 matplotlib 등에서 오른쪽 그림을 만드는 절차를 소개합니다.
 
양 로그 스케일에서 plot을 다룬 기사. 선형 스케일과 양 로그 스케일은 bin 나누기와 fitting 부분이 다릅니다.
환경
파이썬 3.9
Numpy 1.20.1
Pandas 1.2.0
Matplotlib 3.3.3
scikit-learn 0.24.1
방법
import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
데이터 개요
데이터가 pandas의 DataFrame에 있다고 가정합니다.
print(df.head())
output
          x         y
0  0.086787  0.296361
1  0.379250  1.195589
2  0.099694  0.207927
3  0.902494  2.255489
4  0.890014  2.071342
binning, mean&std/quantile 계산, fitting
# 例えばxをbin幅 1/bins=1/20 で分割したい時
bins=20
df['xbin']=round(bins*df.x)/bins
# mean&std/quantilesの計算
m=df.groupby('xbin').mean()
s=df.groupby('xbin').std()
# 1次関数でfitting
c=np.polyfit(m.index,m.y,1)
l=np.poly1d(c)(m.index)
r2=r2_score(l,m.y)
print(df.head())
output
          x         y  xbin
0  0.086787  0.296361   0.1
1  0.379250  1.195589   0.4
2  0.099694  0.207927   0.1
3  0.902494  2.255489   0.9
4  0.890014  2.071342   0.9
plot
plt.rcParams['font.family'] = 'Arial' 
plt.rcParams['mathtext.fontset'] = 'stix' 
plt.rcParams['font.size'] = 15 
plt.rcParams['xtick.labelsize'] = 9 
plt.rcParams['ytick.labelsize'] = 9 
plt.rcParams['xtick.direction'] = 'in' 
plt.rcParams['ytick.direction'] = 'in' 
plt.rcParams['axes.linewidth'] = 0.7 
plt.rcParams['axes.grid'] = False 
plt.title('binned errorbar plot test: linear')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.errorbar(m.index, m.y, yerr=s.y, fmt='o', marker='s', mfc='#000000', mec='#000000', 
             ecolor='#2e3436', elinewidth=0.5, capsize=1.0, capthick=1.0)
plt.plot(m.index,l, color='#2e3436', linestyle=':')
plt.text(max(m.index)/3.7, max(m.y)*6/8, '$y$={:.2f}$x$ + {:.2f}, \n$R^2$={:.2f}'.format(c[0], c[1], r2), fontsize=15)
plt.savefig('test_linear.pdf')
이 방법으로 시작 부분의 오른쪽 그림
test_linear.pdf을 얻었습니다.배경
이번에 사용한 예에서는 고난이 전해지기 어려웠을지도 모르지만, 산점도 그 자체를 사용하면 이상치의 영향으로 인해 혼잡해지는 경우가 존재한다. 표준 편차/사분위를 사용하여 멋지게 보이게 할 수 있습니다.
링크
다음 두 링크로 공부했습니다. 고맙습니다.
matplotlib 오류 막대가있는 그래프 그리기
plt.errorbar를 사용하는 방법과 1 차 함수를 사용한 fitting 예제가 있습니다.Matplotlib로 깨끗한 논문용 그래프 만들기
plt.rcParams['hoge']를 사용하여 matplotlib의 기본 설정을 변경하여 멋지게 볼 수 있습니다.
                Reference
이 문제에 관하여(binned errorbar plot with matplotlib), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/HajimeKoike/items/1580157feecdf7aa562d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)