pandas 라이브러리
pandas 그래프
- pandas 만으로는 그래프 출력을 할 수없음. matplotlib 패키지와 함께 해야됨
1. padnas 그래프 구조
- pandas의 Series나 Dataframe으로 생성한 데이터가 있을 경우에는 pandas 모듈로 그래프를 그릴수있다.
Series_data.plot([kind = 'graph_kind'] [,option ]) []옵션
DataFrame_data.plot([x=label 혹은 potion,
y=label 혹은 potions ,]
[kind = 'graph_kind'] [, option ]) []옵션
Series_data.plot(kind = 'line')
: 선그래프
- kind 옵션을 생략하면 기본적으로 선 그래프가 그려짂다
2. pandas 그래프 종류
kin옵션 | 의미 |
---|---|
line | 선 그래프(기본) |
bar | 수직 막대 그래프 |
barh | 수평 막대 그래프 |
scatter | 산점도(DataFrame 데이터만 가능) |
hist | 히스토그램 |
pie | 파이 그래프 |
3.pandas 그래프 그리기
DataFrame_data.plot(kind='line')
= DataFrame_data.plot.line()
DataFrame_data.plot(kind='bar')
= DataFrame_data.plot.bar()
DataFrame_data.plot(kind='pie')
= DataFrame_data.plot.pie()
DataFrame_data.plot.hist()
DataFrame_data.plot.scatter()
1) line_graph
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import platform
from matplotlib import font_manager, rc
if platform.system() == 'Darwin':
rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
# %%
# 기본 선 그래프
# Series 생성
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)
s.plot()
plt.show()
# %%
s = pd.Series([1,2,3,4,5,6,7,8,9,10],
index=pd.date_range('2019-01-01', periods=10))
print(s)
s.plot()
plt.show()
# %%
# 격자모양 추가
s.plot(grid=True)
plt.show()
2) bar_graph
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import platform
from matplotlib import font_manager, rc
if platform.system() == 'Darwin':
rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
# %%
# 데이터 세트 만들기 (난수 10행 3열 발생)
data_set = np.random.rand(10,3)
print(data_set)
# %%
# 데이터 프레임 생성
df = pd.DataFrame(data_set)
print(df)
# %%
# 컬럼 만들기
df = pd.DataFrame(data_set, columns=['A', 'B', 'C'])
print(df)
# %%
# 막대 그래프 그리기
df.plot(kind='bar')
plt.show()
# %%
# 수평 그래프
df.plot(kind='barh')
plt.show()
# %%
# 영역 그래프
df.plot(kind='area', stacked=False)
plt.show()
# %%
grade_num = [5, 14, 12, 3]
students = ['A', 'B', 'C', 'D']
df_grade = pd.DataFrame(grade_num, index=students, columns=['Students'])
print(df_grade)
grade_bar = df_grade.plot.bar(grid=True)
grade_bar.set_xlabel('학점')
grade_bar.set_ylabel('학생수')
grade_bar.set_title('학점별 학생 수 막대 그래프')
plt.show()
3. scatter
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import platform
from matplotlib import font_manager, rc
if platform.system() == 'Darwin':
rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
# %%
temperature = [25.2, 27.4, 22.9, 26.2, 29.5, 33.1, 30.4, 36.1, 34.4, 29.1]
ice_cream_sales = [236500, 357500, 203500, 365200, 446600, 574200, 453200, 675400, 598400, 463100]
dict_data = {'기온' : temperature, '아이스크림 판매량' : ice_cream_sales}
df_ice_cream = pd.DataFrame(dict_data, columns=['기온', '아이스크림 판매량'])
print(df_ice_cream)
df_ice_cream.plot.scatter(x='기온', y='아이스크림 판매량',
grid=True,
title='최고 기온과 아이스크림 판매량')
plt.show()
4) histogram
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import platform
from matplotlib import font_manager, rc
if platform.system() == 'Darwin':
rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
# %%
math = [76,82,84,83,90,86,85,92,72,71,100,87,81,76,94,78,81,60,79,69,74,87,82,68,79]
df_math = pd.DataFrame(math, columns = ['Student'])
print(df_math)
# %%
# 옵션 bins는 계급의 갯수를 의미하며, 기본값은 10이다.
math_hist = df_math.plot.hist(bins=8, grid = True)
math_hist.set_xlabel("시험 점수")
math_hist.set_ylabel("도수(frequency)")
math_hist.set_title("수학 시험의 히스토그램")
plt.show()