728x90
반응형
1. matplot 모듈을 이용한 그래프
2. 남북한발전전력량.xlsx 데이터를 이용하여 연합막대 그래프 그리기
3. 자동차 연비데이터의 mpg 값을 히스토그램으로 출력하기
4. 파이그래프
5. 박스그래프 : 두개의 그래프 출력하기
6. origin 컬럼으로 그룹화하기
7. seaborn 모듈을 이용한 시각화 : matplot의 확장판
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 22 09:27:57 2022
@author: p011v
"""
'''
DataFrame.plot(kind="그래프종류") 함수를 이용하여 그래프 작성
기본 : 선그래프
kind="bar" : 막대그래프
kind="barh" : 수평막대그래프
kind="hist" : 히스토그램
kind="scatter" : 산점도
kind="box" : 박스그래프
'''
##########1. matplot 모듈을 이용한 그래프
#막대그래프
import matplotlib.pyplot as plt
#x축의 값
subject=["Oracle", "Python", "Sklearn", "Tensorflow"]
#y축의 값
score=[65,95,85,95]
fig = plt.figure() #그래프가 그려지는 영역
#ax1 : 그래프 작성영역
ax1 = fig.add_subplot(1,1,1) #그래프의 영역을 분할. 1행, 1열, 1번째 그래프
#bar : 막대그래프
#bar(x축의 값, y축의 값)
ax1.bar(range(len(subject)), score, align="center", color="darkblue")
#x축의 값이 숫자에서 subject 데이터로 변경
plt.xticks(range(len(subject)), subject, rotation=0, fontsize="small")
plt.xlabel("Subject")
plt.ylabel("Score")
plt.title("Class Score")
########## 2. 남북한발전전력량.xlsx 데이터를 이용하여 연합막대 그래프 그리기
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use("ggplot")
df = pd.read_excel("data/남북한발전전력량.xlsx")
df.info()
df
df = df.loc[5:] #북한지역의 발전량만 조회
df
#df.drop("전력량 (억㎾h)", axis=1, inplace=True)
del df["전력량 (억㎾h)"]
df.info()
df.set_index("발전 전력별", inplace=True) #발전 전력별 컬럼을 인덱스로 변경하기
df = df.T #전치행렬 : 행과 열을 바꿈
df.info()
df = df.rename(columns={"합계":"총발전량"}) #합계를 총발전량으로 변경
df.info()
#df["총발전량"].shift(1) : 총발전량의 앞의 인덱스 데이터
#df['총발전량 - 1년'] : 전년도 발전량
df['총발전량 - 1년'] = df["총발전량"].shift(1)
df.info
df
'''
증감률 컬럼 추가
증감률 : (현재데이터 - 전년도데이터) / 전년도데이터 * 100
= 현재데이터/전년도데이터 - 전년도데이터/전년도데이터
'''
df['증감율'] = ((df['총발전량'] / df['총발전량 - 1년']) - 1) * 100
from matplotlib import rc
rc('font', family="Malgun Gothic") #한글폰트 설정
plt.rcParams['axes.unicode_minus'] = False #음수표시를 - 표시로 처리
#width=0.7 : 막대의 넓이
#stacked=False : 막대그래프를 따로 표시
ax1 = df[['수력', '화력']].plot(kind='bar', figsize=(20, 10), \
width=0.7, stacked = False)
#ax1의 영역에 그래프 추가. ax2그래프 영역은 ax1의 영역과 같은 영역으로 설정.
#ax1은 막대, ax2는 선그래프
ax2 = ax1.twinx()
#df.index : x축의 값, df.증감율 : x축의 값
#ls='-' : 선의 종류 실선. 점선 => '--'
ax2.plot(df.index, df.증감율, ls='-', marker='o', markersize=20,
color='green', label='전년대비 증감율(%')
ax1.set_ylim(0, 500) #ax1의 y축 값의 범위지정
ax2.set_ylim(-50, 50) #ax2의 y축 값의 범위지정
ax1.set_xlabel('연도', size=20)
ax1.set_ylabel('발전량(억 KWh')
ax2.set_ylabel('전년 대비 증감율(%')
plt.title('북한 전력 발전량 (1990 ~ 2016)', size=30)
ax1.legend(loc='upper left') #수력, 화력데이터가 범례로 표시. 왼쪽 위쪽 표시
ax2.legend(loc='upper right') #label 속성의 값을 표시. 오른쪽 위쪽 표시
plt.savefig("북한전력량.png", dpi=400, bbox_inches="tight") #그래프를 이미지파일로 생성
plt.show()
########## 3. 자동차 연비데이터의 mpg 값을 히스토그램으로 출력하기
import seaborn as sns
df = sns.load_dataset("mpg")
df.info()
#mpg 데이터를 히스토그램으로 출력하기
#히스토그램 : x축:값의 구간(범위). y축 : 빈도수
#bins=20 : 값의 구간을 20개로 분리
df["mpg"].plot(kind="hist", bins=5, color='coral', figsize=(10, 5))
plt.title("MPG Histogram")
plt.xlabel("mpg")
plt.show()
#weight, mpg 데이터의 산점도 출력하기
#DataFrame.plot() 함수
#c='coral' : 색상지정
#s=20 : 산점도에서 점의 크기
#figsize=(10,5) : 그래프의 크기
df.plot(x="mpg", y="weight", kind="scatter", c='coral', s=20, figsize=(10, 5))
#matplot모듈을 이용하여 산점도 출력
plt.figure(figsize=(10, 5))
plt.scatter(df["weight"], df["mpg"], c="coral", s=20)
# bubble 그래프 : 산점도. 점의 크기를 데이터의 값으로 결정
# 3개의 컬럼(변수)지정함 : x축:weight, y축:mpg, 점의크기: cylinders
# cylinders 데이터 값의 종류와 갯수 조회하기
df["cylinders"].unique()
df["cylinders"].value_counts()
#cylinders 값을 최대값의 비율로 계산하여 데이터 생성
cylinders_size = df["cylinders"] / df["cylinders"].max() * 100
cylinders_size.value_counts()
df.plot(x="weight", y="mpg", kind="scatter", c='coral', \
s=cylinders_size, figsize=(10, 5), alpha=0.7)
#색상으로 데이터값을 설정하기
# marker= '+' : 산점도에 표시되는 점의 모양
# cmap='plasma' : matplot 모듈에 색상 모임. 값에 따른 색상의 목록
# viridis, inferno, magma, cividis
#c=df["cylinders"] : cylinders의 값에 해당하는 색을 cmap에서 색을 선택
df.plot(x="weight", y="mpg", kind="scatter", marker='+', \
figsize=(10, 5), cmap='viridis', c=df["cylinders"], \
s=50, alpha=0.7)
plt.title('Scatter Plot: mpg-weight-cylinders')
#transparrent=True : 투명도를 선택(True:투명, False:불투명)하여 그림으로 저장
plt.savefig("scatter_transparent.png", transparent=True)
plt.show()
########## 4. 파이그래프
# origin 컬럼의 비율을 파이그래프로 출력하기
# origin 컬럼의 값과 값의 갯수를 출력하기
df_origin = df.origin.value_counts()
df_origin
type(df_origin)
'''
autopct="%.1f%%" : 비율표시.
%.1f : 소숫점이하 1자리로
%% : %문자
startangle=10 : 파이조각의 시작 각도
'''
df_origin.plot(kind="pie", figsize=(7, 5), autopct="%.1f%%", startangle=90, \
colors=['chocolate', 'bisque', 'cadetblue'])
plt.title("Model Origin", size=20)
plt.legend(labels = df_origin.index, loc="upper left")
plt.show()
########## 5. 박스그래프 : 두개의 그래프 출력하기
fig = plt.figure(figsize=(15, 5)) #그림판 생성
ax1 = fig.add_subplot(1, 2, 1) #1행 2열 그럼판분리, 1번째 그림판
ax2 = fig.add_subplot(1, 2, 2) #1행 2열 그럼판분리, 2번째 그림판
# boxplot : 박스그래프 작성
df[df['origin']=='usa'] #df 중 origin컬럼의 값이 usa인 데이터만 조회
df[df['origin']=='usa']['mpg'] #df 중 origin컬럼의 값이 usa인 데이터의 mpg 컬럼만 조회
#x = [usa에서 생산된 자동차의 mpg값, japan에서 생산된 자동차의 mpg값, europe에서 생산된 자동차의 mpg값]
ax1.boxplot(x = [df[df['origin']=='usa']['mpg'],
df[df['origin']=='japan']['mpg'],
df[df['origin']=='europe']['mpg']],
labels = ['USA', 'JAPAN', 'EU'])
ax2.boxplot(x = [df[df['origin']=='usa']['mpg'],
df[df['origin']=='japan']['mpg'],
df[df['origin']=='europe']['mpg']],
labels = ['USA', 'JAPAN', 'EU'], vert=False) #vert=False : 박스그래프를 가로 표시
ax1.set_title('제조국가별 연비 분포(수직 박스 플롯)')
ax2.set_title('제조국가별 연비 분포(수직 박스 플롯)')
plt.show()
########## 6. origin 컬럼으로 그룹화하기
# df 데이터를 origin 컬럼으로 그룹화하여 그룹별 합계 출력하기
df_origin = df.groupby("origin").sum() #합계
df_origin
# df 데이터를 origin 컬럼으로 그룹화하여 그룹별 건수 출력하기
df_origin = df.groupby("origin").count() #origin 데이터의 값의 순서로 출력
df_origin
df_origin.value_counts() #건수의 내림차순 출력
# df 데이터를 origin 컬럼으로 그룹화하여 그룹별 평균 출력하기
df_origin = df.groupby("origin").mean() #평균
df_origin
# df 데이터를 origin 컬럼으로 그룹화하여 그룹별 중간값 출력하기
df_origin = df.groupby("origin").median() #중간값
df_origin
########## 7. seaborn 모듈을 이용한 시각화 : matplot의 확장판
# 시각화모듈 + 데이터셋
#선형회귀 그래프 : 산점도 + 회귀도 표시
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset("titanic")
titanic.info()
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
#regplot : 선형회귀그래프 : 산점도 + 회귀선표시
#fit_reg=False : 회귀선 표시 안함
#회귀선 : 모든점에서 가장 가까운 점들을 직선으로 표시
'''
data = titanic : titanic 데이터의 값으로 그래프 출력
x = 'age', y = 'fare' : titanic 데이터 중 x축의 값은 age 컬럼을 y축의 값은 fare 컬럼
ax = ax1 : 그래프 영역
fit_reg=False : 회귀선 표시 안함
'''
sns.regplot(x = 'age', y = 'fare', data = titanic, ax = ax1)
sns.regplot(x = 'age', y = 'fare', data = titanic, ax = ax2, fit_reg=False)
plt.show()
#히스토그램 작성하기
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)
'''
sns.distplot : 밀도, 빈도수 함께 출력할 수 있는 그래프프
sns.kdeplot : 밀도를 출력할 수 있는 그래프프
sns.histplot : 빈도수를 출력할 수 있는 그래프프
'''
# sns.distplot(titanic['fare'], ax = ax1) #kde(밀도), hist(빈도수) 출력
# sns.distplot(titanic['fare'], hist=False, ax = ax1) #kde(밀도) 출력
sns.distplot(titanic['fare'], kde=False, ax = ax1) #hist(빈도수) 출력
sns.kdeplot(x = 'fare', data = titanic, ax = ax2)
sns.histplot(x = 'fare', data = titanic, ax = ax3)
ax1.set_title('titanic fare - distplot')
ax2.set_title('titanic fare - kdeplot')
ax3.set_title('titanic fare - histplot')
plt.show()
# 히트맵 그래프 : 범주형 데이터의 수치를 색상과 값으로 표시
# pivot_table : 2개의 범주형 데이터를 행과 열로 재구분
# aggfunc = 'size' : 데이터의 갯수
table = titanic.pivot_table(index=['sex'], columns=['class'], aggfunc='size')
table
# 성별 인원수
titanic.sex.value_counts()
# 등급별 인원수
titanic['class'].value_counts()
'''
table : 표시할 데이터값
annot=True/False : 데이터값 표시여부, 표시/표시안함
fmt='d' : 10진 정수로 표시
cmap='YlGnBu' : 색상표 설정
linewidth=5 : 여백
cbar=True/False : 컬러바 표시/표시안함
'''
sns.heatmap(table, annot=True, fmt='d', cmap='YlGnBu', linewidth=5, cbar=True)
plt.show()
728x90
반응형
'study > Python' 카테고리의 다른 글
[Python] 37. Test 답 (0) | 2022.06.27 |
---|---|
[Python] 37. Test (0) | 2022.06.22 |
[Python] 36. Test 답 (0) | 2022.06.21 |
[Python] 36. Test (0) | 2022.06.21 |
[Python] 36. pandas(행(index) 추가하기, 정렬하기, seaborn. titanic (조회, 정렬), seaborn. mpg. (상관계수, 시각화[산점도, 히스토그램], 전체행렬), 결측값 처리, matplot : 기본 시각화모듈 (0) | 2022.06.21 |