Python

Python - 데이터프레임에서 바로 그래프 그리기

electronicprogrammer 2020. 11. 1. 14:34

 

이번 포스팅에서는 .csv 파일을 Pandas로 불러와서 만든 데이터프레임에서 간단하게 그래프를 Pie Chart(원 그래프) , Bar Chart (막대 그래프) 를 그리는 방법에 대해서 정리해보겠습니다.

 

먼저 데이터를 pandas를 이용해서 불러오겠습니다.

 

그 다음 데이터 구조를 한 번 확인해보겠습니다.

 

여기서 저희는 이산적인 속성인 sex 속성에 대해서 데이터를 시각화해보고자 합니다.

 

먼저 value_counts() 함수를 이용해서 각 속성의 갯수를 파악할 수 있습니다.

 

이를 이용해서 각 속성과 해당 속성의 대한 갯수를 값으로 해서 그래프를 그릴 수 있습니다.

plt.figure(figsize=(12,5))

plt.title('Data Sex Rate' , fontsize=20)

plt.ylabel('Counts' , fontsize=15)
plt.xlabel('Sex' , fontsize=15)

insurance['sex'].value_counts().plot.bar(color = ['lightblue', 'tomato'])

plt.show()

위에서 insurance['sex].value_counts().plot.bar() 을 함으로써 쉽게 막대 그래프를 그릴 수 있습니다.

 

plt.figure(figsize=(7,5))

plt.title('Data Sex Rate' , fontsize=20)

plt.xlabel('Counts' , fontsize=15)
plt.ylabel('Sex' , fontsize=15)

insurance['sex'].value_counts().plot.barh(color = ['lightblue', 'tomato'])

plt.show()

 

barh 를 함으로써 x , y 축을 반대로 해줄 수 도 있습니다.

 

이제 원형 그래프를 그려보겠습니다.

plt.figure(figsize=(7,7))

plt.title('Data Sex Rate' , fontsize=20)

plt.ylabel('Sex' , fontsize=15)

insurance['sex'].value_counts().plot.pie(autopct = '%.2f%%' , 
                                         colors = ['lightblue', 'tomato'] , 
                                         textprops = {'fontsize' : 12 , 
                                                      'weight' : 'bold'})

plt.show()

 

value_counts().plot.pie() 함수를 통해서 원 그래프를 매우 간단하게 그려볼 수 있었습니다.