Table of Contents
목차
- 그래프 그리기
- matplotlib 라이브러리로 그래프 그리기
- matplotlib 라이브러리 사용
- seaborn 라이브러리 사용
- 데이터프레임과 시리즈로 그래프 그리기
- 데이터 프레임과 시리즈로 그래프 그리기(plot X)
- [시리즈 값으로 그리기(히스토그램)](#시리즈-값으로-그리기(히스토그램)
- 투명도, 간격 조절(히스토그램 일변수에 두개)
- 밀집도, 산점도 그래프, 육각그래프
- box매서드
- 데이터 프레임과 시리즈로 그래프 그리기(plot X)
- Seaborn 라이브러리로 그래프 스타일 정하기
그래프 그리기
matplotlib 라이브러리로 그래프 그리기
Set) %matplotlib notebook
Import matplotlib.pyplot as plt
1>전체그래프가 위치 할 기본 틀 만들기
Fig = pli.figuer()
2>그래프에 그려 넣을 그래프 격자 만들기
기본틀 이름.add_subplot( , , )
3>격자에 그래프 추가
격자이름.plot(함수이름1[‘x’], 함수이름1[‘y’], ‘o’)
4>그래프 격자에 제목 추가 격자이름.set_title(“이름”)
5>기본 틀 제목 추가 기본틀 이름.suptitle(“이름”)
6>각 그래프의 레이아웃 조절 Fig.ti + [TAP]
matplotlib 라이브러리 사용
기본 그래프
Set>
히토그램_일변량 그래프
fig = plt.figure()
axes1 = fig.add_subplot(1, 1, 1)
axes1.hist(tips['total_bill'], bins=10)
axes1.set_title('Histogram of Total Bill')
axes1.set_xlabel('Frequency')
axes1.set_ylabel('Total Bill')
-> bins=10 : x축 간격
산점도 그래프_이변량그래프
scatter_plot = plt.figure()
axes1 = scatter_plot.add_subplot(1, 1, 1)
axes1.scatter(tips['total_bill'], tips['tip'])
axes1.set_title('Scatterplot of Total Bill vs Tip')
axes1.set_xlabel('Total Bill')
axes1.set_ylabel('Tip')
박스 그래프_ 이산형변수(명확)와 연속형 변수(명확X)
boxplot = plt.figure()
axes1 = boxplot.add_subplot(1, 1, 1)
axes1.boxplot(
[tips[tips['sex'] == 'Female']['tip'],
tips[tips['sex'] == 'Male']['tip']],
labels=['Female', 'Male'])
axes1.set_xlabel('Sex')
axes1.set_ylabel('Tip')
axes1.set_title('Boxplot of Tips by Sex')
다변량 그래프
:3개이상의 변수 사용
산점도 그래프_사변량그래프
def recode_sex(sex):
if sex == 'Female':
return 0
else:
return 1
tips['sex_color'] = tips['sex'].apply(recode_sex)
#-> 성별에따라 점의 색
catter_plot = plt.figure()
axes1 = scatter_plot.add_subplot(1, 1, 1)
axes1.scatter(
x=tips['total_bill'],
y=tips['tip'],
s=tips['size'] * 10, -> 점의 크기
c=tips['sex_color'],
alpha=0.5)
axes1.set_title('Total Bill vs Tip Colored by Sex and Sized by Size')
axes1.set_xlabel('Total Bill')
axes1.set_ylabel('Tip')
seaborn 라이브러리 사용
단변량 그래프
Set> import seaborn as sns
tips = sns.load_dataset("tips")
히스토그램, KDE
ax = plt.subplots()
ax = sns.distplot(tips['total_bill'])
ax.set_title('Total Bill Histogram with Density Plot')
확률 KDE
ax = plt.subplots()
ax = sns.distplot(tips['total_bill'], hist=False)
ax.set_title('Total Bill Density')
ax.set_xlabel('Total Bill')
ax.set_ylabel('Unit Probability')
히스토그램
ax = plt.subplots()
ax = sns.distplot(tips['total_bill'], kde=False)
ax.set_title('Total Bill Histogram')
ax.set_xlabel('Total Bill')
ax.set_ylabel('Frequency')
히스토그램, KDE , 양탄자(rug)
hist_den_rug, ax = plt.subplots()
ax = sns.distplot(tips['total_bill'], rug=True)
ax.set_title('Total Bill Histogram with Density and Rug Plot')
ax.set_xlabel('Total Bill')
count(이산값)그래프
ax = plt.subplots()
ax = sns.countplot('day', data=tips)
ax.set_title('Count of days')
ax.set_xlabel('Day of the Week')
ax.set_ylabel('Frequency')
이변량 그래프
산점도 그래프, 회귀선
ax = plt.subplots()
ax = sns.regplot(x='total_bill', y='tip', data=tips)
ax.set_title('Scatterplot of Total Bill and Tip')
ax.set_xlabel('Total Bill')
ax.set_ylabel('Tip')
산점도 그래프
ax = plt.subplots()
ax = sns.regplot(x='total_bill', y='tip', data=tips, fit_reg=False)
ax.set_title('Scatterplot of Total Bill and Tip')
ax.set_xlabel('Total Bill')
ax.set_ylabel('Tip')
산점도 그래프, 히스토그램
joint = sns.jointplot(x='total_bill', y='tip', data=tips)
joint.set_axis_labels(xlabel='Total Bill', ylabel='Tip')
joint.fig.suptitle('Joint Plot of Total Bill and Tip', fontsize=10, y=1.03)
육각형 그래프, 히스토그램
hexbin = sns.jointplot(x="total_bill", y="tip", data=tips, kind="hex")
hexbin.set_axis_labels(xlabel='Total Bill', ylabel='Tip')
hexbin.fig.suptitle('Hexbin Joint Plot of Total Bill and Tip', fontsize=10, y=1.03)
이차원 밀집도
#Shade= 음영
kde, ax = plt.subplots()
ax = sns.kdeplot(data=tips['total_bill'],
data2=tips['tip'],
shade=True)
ax.set_title('Kernel Density Plot of Total Bill and Tip')
ax.set_xlabel('Total Bill')
ax.set_ylabel('Tip')
바 그래프
ax = plt.subplots()
ax = sns.barplot(x='time', y='total_bill', data=tips)
ax.set_title('Bar plot of average total bill for time of day')
ax.set_xlabel('Time of day')
ax.set_ylabel('Average total bill')
박스 그래프
ax = plt.subplots()
ax = sns.boxplot(x='time', y='total_bill', data=tips)
ax.set_title('Boxplot of total bill by time of day')
ax.set_xlabel('Time of day')
ax.set_ylabel('Total Bill')
바이올린 그래프
ax = plt.subplots()
ax = sns.violinplot(x='time', y='total_bill', data=tips)
ax.set_title('Violin plot of total bill by time of day')
ax.set_xlabel('Time of day')
ax.set_ylabel('Total Bill')
관계 그래프
단점= 중복된 그래프 표시
fig = sns.pairplot(tips)
pair_grid = sns.PairGrid(tips)
pair_grid = pair_grid.map_upper(sns.regplot)
pair_grid = pair_grid.map_lower(sns.kdeplot)
pair_grid = pair_grid.map_diag(sns.distplot, rug=True)
plt.show()
다변량 그래프
색상추가
:hue=’’
- 바이올린 그래프
violin, ax = plt.subplots()
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True)
plt.show()
- 산점도 그래프
scatter = sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex', fit_reg=False)
plt.show()
- 관계 그래프
fig = sns.pairplot(tips, hue='sex')
산점도 그래프_ 크기
scatter = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, hue='sex', scatter_kws={'s': tips['size']*10})
plt.show()
산점도 그래프_ 크기와 모양(색상에 따라 o,x)
scatter = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, hue='sex', markers=['o', 'x'], scatter_kws={'s': tips['size']*10})
plt.show()
lmplot 메서드로 4개의 데이터 그룹 한 번에 그리기
col= : 데이터 그룹을 구분할 열
col_wrap= :그래프를 그릴 열의 최댓값
anscombe_plot = sns.lmplot(x='x', y='y', data=anscombe, fit_reg=False)
anscombe_plot = sns.lmplot(x='x', y='y', data=anscombe, fit_reg=False, col='dataset', col_wrap=2)
112
데이터프레임과 시리즈로 그래프 그리기
데이터 프레임과 시리즈로 그래프 그리기(plot X)
ax = plt.subplots()
(일변수)ax = 전체[‘변수’].plot.그래프 종류()
(다변수)ax = 전체.plot.함수이름(x=’변수’, y=’변수’, ax=ax)
시리즈 값으로 그리기(히스토그램)
fig, ax = plt.subplots()
ax = tips['total_bill'].plot.hist()
투명도, 간격 조절(히스토그램 일변수에 두개)
> 투명도: alpha
> X축 간격: bins( 클수록 막대기 얇아짐)
fig, ax = plt.subplots()
ax = tips[['total_bill', 'tip']].plot.hist(alpha=0.5, bins=20, ax=ax)
밀집도, 산점도 그래프, 육각그래프
fig, ax = plt.subplots()
ax = tips['tip'].plot.kde()
fig, ax = plt.subplots()
ax = tips.plot.scatter(x='total_bill', y='tip', ax=ax)
fig, ax = plt.subplots()
ax = tips.plot.hexbin(x='total_bill', y='tip', ax=ax)
fig, ax = plt.subplots()
ax = tips.plot.hexbin(x='total_bill', y='tip', gridsize=10, ax=ax)

#육각형 크기
box매서드
fig, ax = plt.subplots()
ax = tips.plot.box(ax=ax)
Seaborn 라이브러리로 그래프 스타일 정하기
:set_style로 그래프스타일 바꾸기
그래프에 스타일 적용
바이올린 그래프 배경에 줄
sns.set_style('whitegrid')
fig, ax = plt.subplots()
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True)
for문으로 모든스타일 하나씩적용
fig = plt.figure()
seaborn_styles = ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']
for idx, style in enumerate(seaborn_styles):
plot_position = idx + 1
with sns.axes_style(style):
ax = fig.add_subplot(2, 3, plot_position)
violin = sns.violinplot(x='time', y='total_bill', data=tips, ax=ax)
violin.set_title(style)
fig.tight_layout()