728x90
반응형
한글설정
한글 설정을 위해서는 font_manager를 활용해서 한글 font를 운영체제별로 가져와야합니다
from matplotlib import pyplot as plt, font_manager
import numpy as np
import math
#한글 폰트 설정을 위한 방법
# font_manager import
# 윈도우 10에 있는 기본 폰트 파일 경로 설정
import matplotlib
import matplotlib.font_manager as fm
font_location = "c:/Windows/Fonts/LG PC.ttf"
font = fm.FontProperties(fname = font_location).get_name()
matplotlib.rc('font', family=font)
라인 그래프
# 라인 그래프 그리기
#그래프 스타일 설정
plt.style.use('ggplot')
# 빈 페이지를 생성
fig = plt.figure()
# 빈 페이지에 그래프 그릴 영역 설정
ax = fig.add_subplot(111)
# 실적을 그래프로 표현
ax.plot(date, hong, label='홍길동')
ax.plot(date, kang, label='강감찬')
# 축 제목과 범례 그리기
ax.set_title('영업 사원별 월별 실적', fontproperties = font)
ax.set_ylabel('실적(단위 : 원)', fontproperties = font)
ax.set_xlabel('월', fontproperties = font)
ax.legend()
plt.show()
바 그래프
# 막대 그래프 활용하기
# bar charts
import pandas as pd
df = pd.read_csv("c:/dev/temp/5차시/1군전염병발병현황_년도별_2.csv",
encoding='euc-kr', index_col='년도')
df.head(10) #10건
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111)
wt = np.array(range(len(df)))
w = 0.1
for i in df.columns :
ax.bar(wt, df[i], width=w, label=i)
wt = wt + w
ax.set_xticks(np.array(range(len(df))))
ax.set_xticklabels(df.index, fontproperties=font)
ax.set_ylabel('발생 건수', fontproperties=font)
ax.legend()
plt.show()
라인과 바 통합 그래프
# Line Chart
# 주식에서 주가변동과 거래량을 함께 표현하기
s_df = pd.read_csv("c:/dev/temp/5차시/주가변동.csv", encoding='euc-kr', index_col=0)
s_df.head(10)
# First line chart painting
plt.style.use('ggplot')
fig = plt.figure(figsize=(10, 5))
s_ax_1 = fig.add_subplot(111)
s_ax_1.plot(s_df.index, s_df['종가'], color='g', label='주가')
plt.show()
# Line Chart and Bar Chart fusion
# 주식에서 주가변동과 거래량을 함께 표현하기
s_df = pd.read_csv("c:/dev/temp/5차시/주가변동.csv", encoding='euc-kr', index_col=0)
s_df.head(10)
# First line chart painting
plt.style.use('ggplot')
fig = plt.figure(figsize=(10, 5))
s_ax_1 = fig.add_subplot(111)
s_ax_1.plot(s_df.index, s_df['종가'], color='g', label='주가')
#plt.show()
# 1개의 X 축에 2개의 Y축 설정하기
s_ax_2 = s_ax_1.twinx()
s_ax_2.bar(s_df.index, s_df['거래금액'], color='r', label='거래금액', width=2)
# 축과 레이블 값 지정하기
s_ax_1.set_yticks([i * 2000 for i in range(5)])
s_ax_1.set_ylabel('주가')
s_ax_1.set_xlabel('년월')
s_ax_2.set_yticks([i*50000 for i in range(5)])
s_ax_2.set_ylabel('거래금액')
s_ax_1.set_title('주가변동과 거래금액')
#범례설정
s_ax_1.legend(loc=1)
s_ax_2.legend(loc=0)
plt.show()
산포도 그래프
#산포도 그래프
# 주요 영화 평점을 산포도 그래프로 작성하여 평점 패턴 찾기
import pandas as pd
df = pd.read_csv("c:/dev/temp/5차시/ani_info.csv", encoding='euc-kr', index_col='anime_id')
df.head(10)
# 자료에서 vote_no이 8만번이상인 작품만 골라내기
df.loc[df['vote_no']>=80000, ['name','vote_no']]
# vote_no이 60만개 이상이면서 평점이 8점이상인 작품 골라내기
df.loc[df['vote_no']>=600000 & (df['rating']>= 8), ['name', 'rating']]
# 장르별 추출하기
types = df['type'].unique()
# 산포도 그래프로 시각화 하기
fig = plt.figure( figsize=(15,8))
ax = fig.add_subplot(111)
for t in types :
x = df.loc[df['type']==t, 'vote_no']
y = df.loc[df['type']==t, 'rating']
ax.scatter(x,y, alpha=0.5, label=t)
ax.set_title('방영 매체별 산포도', fontproperties=font)
ax.set_xlabel('리뷰 참가 건수', fontproperties=font)
ax.set_ylabel('평점', fontproperties=font)
ax.legend(loc='lower right', fontsize=10)
plt.show()
파이 차트
# pie Chart
import pandas as pd
cdf = pd.read_csv("c:/dev/temp/5차시/1군전염병발병현황_년도별_2.csv",
encoding='euc-kr', index_col='년도')
cdf.head(10) #10건
cdf_2004 = cdf.iloc[2]
cdf_2005 = cdf.iloc[3]
# 2004년과 2005년에 발생한 전염병들을 pie chart로 비교
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# Select a color
color = ("red","green","blue", "yellow")
color2 = ("blue", "white", "black","pink")
ax1.pie(cdf_2004 ,
explode=None ,
labels=cdf_2004.index,
autopct = '%1.0f%%',
colors=color,
startangle=90,
counterclock=False)
ax2.pie(cdf_2005 ,
explode=None ,
labels=cdf_2005.index,
autopct = '%1.0f%%',
colors=color,
startangle=90,
counterclock=True)
ax1.set_title("2004년 전염병 발생현황")
ax2.set_title("2005년 전염병 발생현황")
fig.subplots_adjust(wspace=0.2)
plt.show()
728x90
반응형
SMALL
'개발 이야기' 카테고리의 다른 글
How to use Android.bp using Soong build system (0) | 2022.02.05 |
---|---|
[파이썬 완전정복] nltk package (0) | 2020.07.23 |
[파이썬 완전정복] Matplotlib (0) | 2020.07.19 |
[파이썬 완전정복] 파이썬 GUI [3] - tkinter Button (0) | 2020.07.06 |
[파이썬 완전정복] 파이썬 GUI [2] - tkinter Label (1) | 2020.07.06 |