Python

Python - 그래프 그리기

해변 2022. 11. 10. 17:43

 

기초 그래프 그리기 - 히스토그램
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
print(tips.head())
print(type(tips))
#tips DF는 지불 금액, 팁, 성별, 흡연유무, 요일 시간, 전체 인원 정보


#Histogram 하나의 변수만 사용해 그린 그래프를 "일변량 그래프"라고 한다
fig = plt.figure() #이미지 전체의 영역을 확보
axes1 = fig.add_subplot(1, 1, 1)
axes1.hist(tips['total_bill'], bins=10) 
#x축의 간격은 bins를 이용해 10으로 지정
axes1.set_title('Histogram of Total Bill')
axes1.set_xlabel('Frequency')
axes1.set_ylabel('Total bill')
plt.show()

 

기초 그래프 그리기 - 산점도
#산점도 그래프는 변수 2개를 사용하기에 "이변량 그래프"라고 한다
scatter_plot = plt.figure() #이미지 전체 영역 확보
axes1 = scatter_plot.add_subplot(1, 1, 1)
axes1.scatter(tips['total_bill'], tips['tip'])
#기본틀과 그래프 격자를 만든 후 scatter 메소드에 total_bill, tips 변수 2개 전달
axes1.set_title('Scatterplot of Total Bill vs Tip')
axes1.set_xlabel('Total Bill')
axes1.set_ylabel('Tip')
plt.show()

기초 그래프 그리기 - 박스 그래프
#박스 그래프는 이산형 변수와 연속형 변수를 함께 사용하는 그래프
#Femal, Male = 이산형 변수
#Tip = 명확하게 셀 수 없는 범위의 값
boxplot = plt.figure()
axes1 = boxplot.add_subplot(1, 1, 1)
axes1.boxplot([tips[tips['sex']=='Female']['tip'],
               tips[tips['sex']=='Male']['tip']],
               labels=['Female', 'Male'])
#성별이 Female, Male인 데이터에서 tip열 데이터만 추출하여 전달
#성별 구분을 위한 labels 인잣값으로 각 성별 추가
axes1.set_xlabel('Sex')
axes1.set_ylabel('Tip')
axes1.set_title('Boxplot of Tips by Sex')
plt.show()

 

 

다변량 그래프 그리기

3개 이상의 변수를 사용한 그래프는 '다변량 그래프'라고 한다.

앞에서는 지불 금액과 팁만을 사용해 산점도 그래프를 그렸는데 만약 여기서 성별을 추가하여 산점도 그래프를 표현해야 한다면?

점의 색상을 다르게 표현하면 된다. 혹은 식사 비용을 추가한다면 점의 크기/투명도를 다르게 하는 방법을 이용할 수도 있다

 

산점도 그래프를 다변량 데이터 - 다변량 그래프로 만들어보자