Violin Plot은 데이터의 분포를 파악하고 싶을 때 사용하면 유용하다.
그래프는 Python의 내장 데이터인 excerise 데이터를 이용하고, 운동의 종류(kind)에 따른 심박수(pulse)의 분포를 파악해 볼 것이다.
df = sns.load_dataset('exercise')
df
- Seaborn 모듈을 활용한 Violin Plot
import seaborn as sns
sns.violinplot(df.kind, df.pulse)
sns.violinplot(df.kind, df.pulse, palette = 'cool')
- palette 파라미터를 이용해서 분포의 색상을 변경할 수 있다.
sns.violinplot('kind', 'pulse', hue = 'diet', data = df, palette = 'cool', split = True)
- hue에 diet변수를 지정해 주면 diet의 종류('low fat', 'no fat') 에 따라 각각 분포를 비교해 볼 수 있다.
- split을 True로 지정하면 diet로 구분 되어 그려지는 것이 아닌, kind별로 한 분포의 양쪽에 나뉘어 그래프가 그려진다.
아래의 튜토리얼을 확인해보면 Violin Plot의 더 많은 파라미터들이 나온다. 다양한 파라미터들을 추가해서 원하는 그래프를 그릴 수 있다 :)
https://seaborn.pydata.org/generated/seaborn.violinplot.html
seaborn.violinplot — seaborn 0.11.1 documentation
The method used to scale the width of each violin. If area, each violin will have the same area. If count, the width of the violins will be scaled by the number of observations in that bin. If width, each violin will have the same width.
seaborn.pydata.org
2. Matplotlib 모듈을 활용한 Violin Plot
Matplolib 모듈을 사용할 때, Seaborn과 같이 그대로 데이터를 입력하면 아래의 오류가 발생한다.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.violinplot(df.kind, df.pulse)
UFuncTypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')
따라서, kind 변수의 범주를 나누고 데이터를 하나로 만들어 준 다음에 그래프를 그린다.
import matplotlib.pyplot as plt
import numpy as np
# Combine the data
data = [df.loc[df['kind'] == 'rest', 'pulse'], df.loc[df['kind'] == 'walking', 'pulse'],
df.loc[df['kind'] == 'running', 'pulse']]
fig, ax = plt.subplots()
ax.violinplot(data)
ax.set_xticks(np.arange(1, 4))
ax.set_xticklabels(['rest', 'walking', 'running']) # Data Labeling
ax.set_xlabel('Kind')
ax.set_ylabel('Pulse')
import matplotlib.pyplot as plt
import numpy as np
data = [df.loc[df['kind'] == 'rest', 'pulse'], df.loc[df['kind'] == 'walking', 'pulse'],
df.loc[df['kind'] == 'running', 'pulse']]
fig, ax = plt.subplots()
# Specifying Means and Quantiles
violinplot_data = ax.violinplot(data, showmeans=True,
quantiles = [[0.25, 0.75], [0.25, 0.75], [0.25, 0.75]])
ax.set_xticks(np.arange(1, 4))
ax.set_xticklabels(['rest', 'walking', 'running'])
ax.set_xlabel('Kind')
ax.set_ylabel('Pulse')
# Setting the edge colors
violinplot_data['cbars'].set_edgecolor('gray')
violinplot_data['cmaxes'].set_edgecolor('black')
violinplot_data['cmins'].set_edgecolor('black')
violinplot_data['cmeans'].set_edgecolor('red')
- showmeans를 True로 하면, 분포에 평균 값을 표시할 수 있다. (빨간색 선)
- quantile 파라미터로 1분위수(0.25)와 3분위수(0.75)를 표시했다. 분위수는 숫자를 변경하여 원하는대로 표시할 수 있다. (파란색 선)
- 검정색 선은 최솟값과 최댓값을 표시한 것이다.
import matplotlib.pyplot as plt
import numpy as np
data = [df.loc[df['kind'] == 'rest', 'pulse'], df.loc[df['kind'] == 'walking', 'pulse'],
df.loc[df['kind'] == 'running', 'pulse']]
fig, ax = plt.subplots()
violinplot_data = ax.violinplot(data)
ax.set_xticks(np.arange(1, 4))
ax.set_xticklabels(['rest', 'walking', 'running'])
ax.set_xlabel('Kind')
ax.set_ylabel('Pulse')
# Setting the face colors
violinplot_data['bodies'][0].set_facecolor('purple')
violinplot_data['bodies'][1].set_facecolor('yellow')
violinplot_data['bodies'][2].set_facecolor('red')
- bodies 파라미터를 이용해서 각각의 분포 색상을 정할 수 있다.
두 가지 모듈을 활용해서 Violin Plot을 그려보았는데, 개인적으로는 Seaborn으로 그리는 것이 눈에 더 잘 들어오고 편리한 것 같다!
[참고: https://codetorial.net/matplotlib/violin_plot.html]
'DIY Data Science > Visualization' 카테고리의 다른 글
[Visualization][Basic] Bar Chart(막대 그래프) (0) | 2021.07.15 |
---|---|
[Visualization][Basic] Pie Chart(원 그래프) (0) | 2021.07.14 |
댓글