★막대그래프, Pie, Line★[Python]★기초통계학-[Chapter02 - 연습문제_05]
2022. 12. 1. 15:03
728x90
반응형
import platform
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
import seaborn as sns
%precision 3
from matplotlib import pyplot as plt
%matplotlib inline
#그래프를 주피터 놋북에 그리기 위해
import numpy as np
import copy
from scipy.stats import probplot
from scipy import stats
#히스토그램 그리기
# Window
if platform.system() == 'Windows':
matplotlib.rc('font', family='Malgun Gothic')
elif platform.system() == 'Darwin': # Mac
matplotlib.rc('font', family='AppleGothic')
else: #linux
matplotlib.rc('font', family='NanumGothic')
# 그래프에 마이너스 표시가 되도록 변경
matplotlib.rcParams['axes.unicode_minus'] = False
# 한글 폰트 설정
font_location = 'C:/Windows/Fonts/MALGUNSL.TTF' #맑은고딕
font_name = font_manager.FontProperties(fname=font_location).get_name()
rc('font',family=font_name)
1. 도시 별 재정자립도 막대, 선 , 원 그래프 그리기
city = '서울 부산 대구 인천 광주 대전 울산 세종 경기 강원 충북 충남 전북 전남 경북 경남 제주'
zarib = '88.8 56.6 51.8 67.3 45.4 57.5 70.7 38.8 71.6 26.6 34.2 36.0 25.7 21.7 28.0 41.7 30.6'
city = list(city.split(' '))
zarib = list(map(float , zarib.split(' ')))
print(city)
print(zarib)
print(len(city))
print(len(zarib))
a = pd.DataFrame([zarib] , columns = city)
a =a.transpose().reset_index()
a.rename(columns = {'index': '도시', 0 : '재정자립도'} , inplace =True)
a
fig = plt.figure(figsize=(12,12))
ax = plt.plot(figsize = (8,8))
fig.set_facecolor('white')
ax = sns.barplot(x=a['도시'] , y=a['재정자립도'])
ax.set_title('도시별 재정자립도')
ax.set_xlabel('도시명' , rotation = 0 , fontsize= 15 , labelpad=18)
ax.set_ylabel('재정자립도', rotation = 0 , fontsize = 15 , labelpad=18)
ax.set_xticklabels(city, rotation = 0 , fontsize= 15)
width = 0.5
for bar in ax.patches:
x = bar.get_x() # 막대 좌측 하단 x 좌표
old_width = bar.get_width() # 기존 막대 폭
bar.set_width(width) # 폭변경
bar.set_x(x+(old_width-width)/2) # 막대 좌측 하단 x 좌표 업데이트
for i,txt in enumerate(a['재정자립도']):
b = txt
print(b)
if b == max(a['재정자립도']):
ax.text(i, b+0.4, str(txt)+'%' , ha='center' , color = 'red' , fontweight = 'bold' , fontsize=17)
#어디 막대, 막대기의 위쪽에
else:
ax.text(i, b+0.5, str(txt)+'%' , ha='center' , color = 'dimgray' , fontsize=13 , fontweight = 'bold')
plt.show()
plt.show()
fig = plt.figure(figsize=(12,12))
ax = plt.plot(figsize = (8,8))
fig.set_facecolor('white')
ax = sns.lineplot(x=a['도시'] , y=a['재정자립도'] , color='r', linestyle='-', marker='o')
ax.set_title('도시별 재정자립도')
ax.set_xlabel('도시명' , rotation = 0 , fontsize= 15 , labelpad=18)
ax.set_ylabel('재정자립도', rotation = 0 , fontsize = 15 , labelpad=18)
ax.set_xticklabels(city, rotation = 0 , fontsize= 15)
fig = plt.figure(figsize=(8,8))
fig.set_facecolor('white')
colors = sns.color_palette('bright')[0:5]
plt.pie(b.loc[:,'재정자립도'] , labels=b.loc[:,'도시'], labeldistance=0.8, autopct='%.1f%%' ,textprops={'fontsize' : 12, 'fontweight' : 'bold'})
출처 : [쉽게 배우는 생활속의 통계학] [북스힐 , 이재원]
※혼자 공부 정리용
728x90
반응형
'기초통계 > 막대그래프,히스토그램' 카테고리의 다른 글
★axhline★막대그래프 기준선[Python]★기초통계학-[Chapter02 - 연습문제_04] (0) | 2022.12.01 |
---|---|
★Pie Chart[Python]★기초통계학-[Chapter02 - 연습문제_03] (0) | 2022.12.01 |
Plt, Fig, Seaborn 이해[Python]★기초통계학-[Chapter02 - 연습문제_02] (0) | 2022.11.30 |
★zip, collections.Counter()★도수표, 도수막대그래프★Plt, Fig, Seaborn 이해[Python]★기초통계학-[Chapter02 - 연습문제] (0) | 2022.11.30 |
★산점도 그래프★이변량 양적자료★기초통계학-[Chapter02 - 03] (0) | 2022.11.30 |