주피터 노트북에서 시각화를 할 때는 항상 아래 명령을 입력해서 그래프가 노트북 안에 포함되도록 한다.
%matplotlib inline
seaborn 은 Python 시각화에 가장 많이 사용되는 라이브러리 중에 하나이다. seaborn 은 matplotlib 를 기반으로 한다.
import seaborn as 눈
from matplotlib import pyplot as plt
9.1. 데이터 불러오기
실습에 사용할 데이터는 iris 데이터이다. iris 데이터는 seaborn 에 내장되어 있어 아래 명령으로 불러올 수 있다.
df = sns.load_dataset('iris')
위의 명령이 안될 경우 https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv 에
서 다운 받은 다음 pandas 로 직접 읽어들인다.
import pandas
df = pandas.read_csv('iris.csv')
어떤 방법으로든 데이터를 불러왔으면 데이터의 내용을 확인해보자
9.2. 산점도
먼저 꽃잎의 길이와 꽃받침의 길이를 산점도로 나타내보자.
sns.regplot(x=df["sepal_length"], y=df["petal_length"]
9.3. 색상
색상을 빨간색으로 바꿔보자.
sns.regplot(x=df["sepal_length"], y=df["petal_length"], color='red')
선의 속성만 바꾸려면 line_kws에 설정값을 사전 형태로 넘겨준다.
sns.regplot(x=df["sepal_length"], y=df["petal_length"], line_kws={'color': 'red'}
점의 속성만 바꾸려면 scatter_kws에 설정값을 사전 형태로 넘겨준다.
sns.regplot(x=df["sepal_length"], y=df["petal_length"], scatter_kws={'color': 'red'}
색상에는 색상 코드를 사용할 수 있다. 색상 코드는 구글에서 "color picker"를 검색하자.
sns.regplot(x=df["sepal_length"], y=df["petal_length"], color='#f49842'
9.4. 선 없애기
fit_reg 옵션으로 회귀선을 제거할 수 있다
sns.regplot(x=df["sepal_length"], y=df["petal_length"], fit_reg=False)
9.5. 옵션
자세한 내용은 공식 문서를 참고하자. https://seaborn.pydata.org/generated/seaborn.regplot.html
line_kws 와 scatter_kws 에 넘길 수 있는 옵션은 다음 링크를 참고하자.
• https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html
• https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html
9.6. 그래프의 속성 바꾸기
matplotlib 에는 피겨(figure)와 액시즈(axes)라는 개념이 있다.
피겨는 그림을 가리키고, 액시즈는 그림에 포함된 하나 의 그래프를 가리킨다.
seaborn 의 그래프 함수들은 해당 그래프의 액시즈를 반환한다. 만약 그래프의 속성을 바꾸고 싶으면 해당 액시즈를 이용한다.
자세한 내용은 matplotlib 의 https://matplotlib.org/api/axes_api.html 를 참고한다_api.html 를 참고한다
9.6.1. 축 이름 붙이기
축 이름은 set_xlabel 과 set_ylabel 로 붙인다.
ax.set_xlabel('Sepal Length’)
ax.figure # 그림을 현재 셀에서 다시 보여준다
한글을 사용하면 글자가 깨진다.
ax.set_xlabel('꽃잎 길이’)
ax.figure
9.7. 글꼴 설정
다음과 같이 글꼴을 한글 글꼴로 바꿔준다.
plt.rc('font', family='Malgun Gothic')
다시 그래프를 그리면 한글이 잘 표시된다.
ax = sns.regplot(x=df["sepal_length"],
y=df["petal_length"]) ax.set_xlabel('꽃잎 길이’)
ax.set_ylabel('꽃받침 길이')
위의 그래프를 자세히보면 왼쪽 아래 마이너스 표시가 깨지는 것을 볼 수 있다.
이것은 한글 폰트에 마이너스가 없기 때문에 생기는 현상이다.
다음과 같이 해주면 된다.
plt.rc('font', family='Malgun Gothic’)
plt.rc('axes', unicode_minus=False)
ax = sns.regplot(x=df["sepal_length"],y=df["petal_length"])
ax.set_xlabel('꽃잎 길이’)
ax.set_ylabel('꽃받침 길이')
9.8. 글꼴 이름 찾기
from matplotlib.font_manager import fontManager
forfontinfontManager.ttflist:
if'Nanum'infont.name:
print(font.name)
아래와 같이 글꼴 이름에 Nanum이 들어가는 경우를 찾는다.
ax.figure 를 통해 그림 속성을 바꿀 수도 있다.
matplotlib 의 Figure 문서 참고
ax = sns.regplot(x=df["sepal_length"],y=df["petal_length"])
ax.figure.set_size_inches(12, 10)
9.9. 그림 속성 바꾸기
9.10. 저장
그림을 저장하는 것도 피겨의 기능이다.
ax = sns.regplot(x=df["sepal_length"], y=df["petal_length"]
9.11. 그래프의 스타일 조정
색상 등 그래프의 스타일을 조정할 경우 시본의 스타일 설정 기능을 사용한다. 자세한 내용은
https://seaborn.pydata.org/tutorial/aesthetics.html
문서를 참고한다.
sns.set_style('darkgrid’)
sns.regplot(x=df["sepal_length"], y=df["petal_length"])
다음 명령으로 기본 스타일로 돌아올 수 있다
9.12. 히스토그램과 밀도 그래프
산점도 두 변수의 관계를 보여준다면 히스토그램과 밀도 그래프는 한 변수의 분포를 보여준다.
sns.distplot(df["sepal_width"])
bins 옵션으로 막대의 갯수를 조절할 수 있다.
sns.distplot(df["sepal_width"], bins=4)
또는 구간을 명시할 수도 있다.
sns.distplot(df[ "sepal_width“ ], bins = [2 , 2.5, 3, 3.5, 4, 4.5, 5])
kde=False 을 넘겨주면 밀도 그래프를 그리지 않는다.
sns.distplot(df["sepal_width"], kde=False)
hist=False 을 넘겨주면 히스토그램을 그리지 않는다.
sns.distplot(df["sepal_width"], hist=False)
자세한 내용은 https://seaborn.pydata.org/generated/seaborn.distplot.html
를 참고하자