Ch9. 그래프와 시각화
SUBPLOT matplotlib 에서 그래프는 figure 객체 내에 존재한다. 해당 figure안에서 그래프를 그릴 수 없다. 그래프를 그리기 위해서는 add_subplot을 사용해서 최소 하나 이상의 subplot을 생성해야 하며, 하나의 subplot에서는 하나의 시각화를 나타낼 수 있다. (단, 서브플롯에 계속 다른 그래프를 그리면, 기존 그래프 위에 새로 생성된다. )
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
-- 3개의 그래프(ax1,ax2,ax3)가 나온다. (2,2,4)는 2x2배열에 4번째 그래프를 mㅣ
_=ax1.hist(np.random.randn(100),bins=20,color='k',alpha=0.3)
-- hist : 히스토그램 그래프 , alpha는 투명
ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30))
-- scatter : 산점도 그래프,
plt.plot(np.random.randn(50).cumsum(),'k--')
--'k--'는 점선, 'ko--'는 점선에 마커를 표기
--drawstyle 옵션으로 선 모형 등을 바꿀 수 있다

subplots_adjust : 서브플롯간의 간격, 위치 및 크기 조정 ex) subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
이외에 x축 눈금 표기 (x대신 y를 써서 y축에 대해 진행할 수 있다)
ticks=ax.set_xticks([0, 250, 500, 750, 1000])
labels=ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
rotation = 30, fontsize = 'small')
범례는 ax.legend() 또는 plt.legend() 로 생성 주석과 글자는 text.arrow , annotate 함수 이용 그림, 도형 추가
fig = plt.figure()
ax=fig.add_subplot(1,1,1)
rect = plt.Rectangle((0.2,0.75),0.4,0.15,color='k', alpha = 0.3)
circ = plt.Circle((0.7, 0.2),0.15, color = 'b', alpha = 0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35, 0.4], [0.2 , 0.6]], color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)

plt.savefig() : 활성화된 그래프를 파일로 저장. 파일로 저장뿐만 아니라 BytesIO처럼 파일과 유사한 객체에 저장하는 것도 가능
ex) plt.savefig('figpath.png, dpi=400, bbox_inches=tight)
그래프간 최소 공백을 가지는 400DPI짜리 png 파일로 저장된다
seaborn
라이브러리 Series 와 DataFrame 에서 사용 가능.
DataFrame의 plot 메서드는 하나의 서브플롯 안에 각 컬럼별로 선그래프를 그리고 자동적으로 범례 생성
ex)
df=pd.DataFrame(np.random.randn(10,4).cumsum(0),
columns=['A','B','C','D'],
index=np.arange(0,100,10))
df.plot()

Series.plot 메서드 인자 label, ax, style, alpha, kind, logy, use_index, rot, xticks, yticks, xlim, ylim, grid
DataFrame의 plot 메서드 인자 subplots, sharex, sharey, figsize, title, legend, sort_columns
막대 그래프
plot.bar( ) : 수직 막대 그래프 plot.barh( ) : 수평 막대 그래프 누적막대그래프는 stacked=True 옵션 사용
ex)
df=pd.DataFrame(np.random.rand(6,4),
index=['one','two','three','four','five','six'],
columns=pd.Index(['A','B','C','D'],name='Genus'))
df.plot.bar()

ex) 두개의 다른 표준정규분포로 이루어진 양봉분포
import seaborn as sns
comp1=np.random.normal(0,1,size=200)
comp2=np.random.normal(10,2,size=200)
values=pd.Series(np.concatenate([comp1, comp2]))
sns.distplot(values,bins=100,color='k')

산포도 : regplot() 메서드 사용 패싯 그리드 : factorplot 함수 사용. 범주형 값을 가지는 데이터를 시각화 하는 방법
이외에도 웹 브라우저 상에서 동적 대화형 그래프인 Bokeh, Plotly 같은 도구도 있다.
Last updated
Was this helpful?