[Python] 그룹별 산점도 점 색깔과 모양 다르게 하기 (Scatter Plot by Groups) (2/4)
Python 분석과 프로그래밍/Python 그래프_시각화 2019. 1. 13. 18:56이번 포스팅은 두 개의 연속형 변수에 대한 관계를 파악하는데 유용하게 사용할 수 있는 산점도(Scatter Plot) 의 두번째 포스팅으로서 그룹별로 산점도의 점의 색깔과 모양을 다르게 하는 방법을 소개합니다.
(2) 그룹별 산점도 (Scatter Plot by Groups)
(3) 산점도의 marker 크기 및 색깔, 모양 설정 (Setting Marker's size, color, shape)
(4) 산점도 행렬 (Scatter Plot Matrix)
산점도를 그리는데 사용할 데이터는 iris 로서, 'petal length'와 'petal width'의 연속형 변수에 대해서 'species' 그룹별로 점의 색깔과 모양을 다르게 설정해보겠습니다.
참고로 species 에는 setosa 50개, versicolor 50개, virginica 50개씩의 관측치가 들어있습니다.
# importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.rcParams['figure.figsize'] = [10, 8] # setting figure size
|
# loading 'iris' dataset from seaborn iris = sns.load_dataset('iris') iris.shape (150, 5)
iris.head()
iris.groupby('species').size() species
setosa 50
versicolor 50
virginica 50
dtype: int64 |
(1) matplotlib 으로 그룹별 산점도 그리기 (scatter plot by groups via matplotlib) |
# Scatter plot with a different color by groups groups = iris.groupby('species') fig, ax = plt.subplots() for name, group in groups: ax.plot(group.petal_length, group.petal_width, marker='o', linestyle='', label=name) ax.legend(fontsize=12, loc='upper left') # legend position plt.title('Scatter Plot of iris by matplotlib', fontsize=20) plt.xlabel('Petal Length', fontsize=14) plt.ylabel('Petal Width', fontsize=14) plt.show() |
(2) seaborn 으로 그룹별 산점도 그리기 (scatter plot by groups via seaborn) |
코드가 깔끔하고 가독성이 좋으며, 산점도 그래프도 보기에 참 좋습니다.
# Scatter plot by Groups sns.scatterplot(x='petal_length', y='petal_width', hue='species', # different colors by group style='species', # different shapes by group s=100, # marker size data=iris) plt.show() |
혹시 AttributeError: module 'seaborn' has no attribute 'scatterplot' 에러가 나면 seaborn version upgrade를 해주시기 바랍니다.
# error: AttributeError: module 'seaborn' has no attribute 'scatterplot' # solution: upgrade seaborn pip install --upgrade seaborn
|
(3) pandas로 그룹별 산점도 그리기 (scatter plot by groups via pandas) |
# adding 'color' column iris['color'] = np.where(iris.species == 'setosa', 'red', np.where(iris.species =='versicolor', 'green', 'blue')) # scatter plot iris.plot(kind='scatter', x='petal_length', y='petal_width', s=50, # marker size c=iris['color']) # marker color by group plt.title('Scatter Plot of iris by pandas', fontsize=20) plt.xlabel('Petal Length', fontsize=14) plt.ylabel('Petal Width', fontsize=14) plt.show() |
많은 도움이 되었기를 바랍니다.
이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾹 눌러주세요. ^^
다음번 포스팅에서는 산점도의 marker 크기 및 색깔, 모양 설정 (Setting Marker's size, color, shape) 에 대해서 소개하겠습니다.
'Python 분석과 프로그래밍 > Python 그래프_시각화' 카테고리의 다른 글
[Python] 산점도 행렬 (Scatterplot Matrix) (4/4) (0) | 2019.01.15 |
---|---|
[Python] 4개 변수로 점의 크기와 색깔을 다르게 산점도 그리기 (Scatter plot with 4 variables, different size & color) (3/4) (0) | 2019.01.13 |
[Python] 그룹별 산점도 점 색깔과 모양 다르게 하기 (Scatter Plot by Groups) (2/4) (3) | 2019.01.13 |
[Python] 산점도 그래프 (Scatter Plot) (1/4) (0) | 2019.01.13 |
[Python] 원 그래프 (Pie Chart), 하위 그룹을 포함한 도넛 그래프 (Donut Chart with Subgroups) (0) | 2019.01.12 |
[Python] 막대 그래프 (Bar Chart) (0) | 2019.01.11 |
댓글을 달아 주세요
안녕하세요! scatter plot 만드는 중인데 도움이 많이되었습니다! 감사합니다
컬러 세팅 관련하여 질문이 있습니다.
마지막 plot(3번)에서 color 컬럼 추가할때 조건을 iris.species == 'setosa' 이면 red, 그 외는 랜덤으로 컬러를 지정하게 하려면 어떻게 해야 할까요?
세부적으로 커스터마이징하는게 쉽지가 않네요 ㅎㅎ ㅠㅠ
알려주시면 감사하겠씁니다!
안녕하세요 임월드님,
numpy로 난수 발생 시키고, for loop과 if else 조건절 섞어서 setosa 외 나머지는 랜덤 칼러로 지정하는 코드 짜보았습니다. 참고하시구요.
for i in range(len(iris.index)):
col_list = ['blue', 'green', 'cyan', 'magenta', 'yellow', 'black']
rand_num = int(np.random.randint(low=0, high=len(col_list), size=1))
if iris.loc[i, 'species'] == 'setosa':
iris.loc[i, 'color'] = 'red'
else:
iris.loc[i, 'color'] = col_list[rand_num]
# scatter plot
iris.plot(kind='scatter',
x='petal_length',
y='petal_width',
s=50, # marker size
c=iris['color']) # marker color by group
감사합니다~! 참고해서 작성해보겠습니다!!^^