일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- DataFrame
- Slicing
- SQL
- INSERT
- 자료구조
- pandas
- 통계학
- 리스트
- 스터디노트
- 순열
- python
- 등비수열
- 문제풀이
- 기계학습
- tree.fit
- pandas filter
- 재귀함수
- numpy
- barh
- matplotlib
- 머신러닝
- pandas 메소드
- 등차수열
- 조합
- plt
- Folium
- 파이썬
- MacOS
- Machine Learning
- maplotlib
Archives
- Today
- Total
코딩하는 타코야끼
[Matplotlib] 4강_Pandas 시각화 본문
728x90
반응형
반응형
1. Pandas 시각화
판다스 자체적으로 matplotlib 를 기반으로 한 시각화기능을 지원한다.
Series나 DataFrame에 plot() 함수나 plot accessor를 사용한다.
📍 plot( )
- kind 매개변수에 지정한 값에 따라 다양한 그래프를 그릴 수 있다.
- kind : 그래프 종류 지정
- 'line' : line plot (default)
- 'bar' : vertical bar plot
- 'barh' : horizontal bar plot
- 'hist' : histogram
- 'box' : boxplot
- 'kde' : Kernel Density Estimation plot
- 'pie' : pie plot
- 'scatter' : scatter plot
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
s = pd.Series([100, 70, 90, 130, 50], index = ['사과', '배', '귤', '수박', '복숭아'])
s
>>>
사과 100
배 70
귤 90
수박 130
복숭아 50
dtype: int64
# plt.figure(figsize = (4,3))
s.plot(kind = 'bar', title = '과일수량', xlabel = '과일종류', ylabel = '개수', figsize = (6,5), rot = 45) # 판다스 //여기서도 적용가능
# plt.title('과일수량') #matplotlib으로 설정
# plt.xlabel('과일')
# plt.ylabel('수량')
plt.show()
📍 막대 그래프
- index가 무슨 값인지를 가리키는 축으로 사용된다.
tips = pd.read_csv('data/tips.csv')
tips.shape
>>>
(244, 7)
cnt_result = tips['day'].value_counts()
cnt_result
>>>
Sat 87
Sun 76
Thur 62
Fri 19
Name: day, dtype: int64
cnt_result.plot(kind = 'bar', title = '요일별 테이블 수', xlabel = '요일', ylabel = '테이블 수', grid = True, rot = 0, figsize = (5,5))
plt.show()
tips['smoker'].value_counts().plot(kind = 'barh', figsize = (5,3), title = '흡연여부에 따른 테이블 수',
color = ['g','r'])
plt.show()
🌓 두개의 분류 별로 그리기
- 여러개의 컬럼일 경우 수평 누적 막대그래프를 그린다.
agg_df = tips.pivot_table(index = 'smoker', columns = 'sex', values = 'tip', aggfunc = 'count') # mean 으로 바꾸면 평균을 구하게 됨.
agg_df
agg_df.plot(kind = 'bar', title = '흡연여부 / 성별 테이블 수', xlabel = '흡연여부', ylabel = '테이블 수', rot = 0)
plt.show()
🌓 요일/성별 손님의 총 수(size)
agg_cu = tips.pivot_table(index = 'sex', columns = 'day', values = 'size', aggfunc = 'sum')
agg_cu
agg_cu.plot(kind = 'bar', title = '요일/성별 손님의 총 수', stacked = True, rot = 0) # stacked = True 차트를 겹겹이 샇는 명령어
plt.legend(bbox_to_anchor = (1,1), loc = 'upper left', title = 'day')
plt.show()
agg_cu.plot(kind = 'bar', subplots= True, figsize = (6,10)) # subplots= True 아래와 같이 나누는 명령어
plt.show()
📍 파이차트
tips['day'].value_counts()
# index : label
# value : 비율계산
>>>
Sat 87
Sun 76
Thur 62
Fri 19
Name: day, dtype: int64
# tips['day'].value_counts(normalize = True) # normalize = True 은 퍼센테이지로 나타내기
tips['day'].value_counts().plot(kind = 'pie', autopct = '%.2f%%', explode = [0,0,0,0.4], shadow = True)
tips.groupby('time')['tip'].mean().plot.pie(autopct = '%.2f%%', shadow = True, explode = [0,0.2])
plt.show()
📍 히스토그램, KDE(밀도그래프)
🌓 hist
# tips['tip'].plot(kind = 'hist', bins = 20)
tips['tip'].plot.hist(bins = 20) # 위 아래 둘다 같은 명령어
plt.show()
tips[['total_bill', 'tip']].plot(kind = 'hist',bins =30, alpha = 0.7)
plt.show()
🌓 kde
tips['tip'].plot(kind = 'kde')
plt.show()
tips[['total_bill', 'tip']].plot(kind = 'kde')
plt.show()
📍 Boxplot (상자그래프)
tips['total_bill'].plot(kind = 'box', whis = 3)
plt.show()
tips[['tip','total_bill']].plot(kind = 'box', figsize = (5,4)) # 두 값을 비교할때 사용
plt.show()
📍 scatter plot (산점도)
# DataFrame 을 이용해서 그린다. (Series는 그릴 수 없다.)
tips.plot(kind = 'scatter', x = 'total_bill', y = 'tip')
plt.show()
📍 Line plot
df = pd.read_excel('data/강수량.xlsx')
df1 = df.set_index('계절').T
df1
# x: index, y: value
df1['봄'].plot(figsize = (10,4), xlabel = '년도', ylabel = '강수량') #kind = 'line' (default)
plt.show()
# dataframe.plot(): index-X, 컬럼별로 선그래프를 그린다.
df1.plot(figsize = (15,4), marker = "." )
plt.show()
df1[['봄', '겨울']].plot()
plt.show()
반응형
'[T.I.L] : Today I Learned > Matplotlib' 카테고리의 다른 글
[Matplotlib] 5강_Seaborn (4) | 2023.05.13 |
---|---|
[Matplotlib] 3강_각종 그래프 그리기_( pie( ), hist( ), boxplot( ) ) (0) | 2023.05.11 |
[Matplotlib] 2강_각종 그래프 그리기_(Scatter Plot / Bar plot) (0) | 2023.05.09 |
[Matplotlib] 2강_각종 그래프 그리기_(Line Plot) (0) | 2023.05.09 |
[Matplotlib] 1강_Matplotlib 개요 (0) | 2023.05.09 |