-
[Data Visualization] 데이터 시각화 - matplotlib(2) : scatter, bar, barhData Science/Data Visualization 2021. 1. 24. 23:30
Dataset
시각화에 앞서 시각화에 사용할 데이터를 불러올게요
seaborn의 Iris 데이터를 사용했습니다.
iris = sns.load_dataset('iris')
Scatter Plot (산점도)
matplotlib.pyplot에서 scatterplot을 그려줍니다.
plt.scatter('sepal_length', # X 'sepal_width', # Y data = iris)
scatterplot의 색을 color로 바꿔주고 alpha로 투명도를 조절합니다.
title, xlabel, ylabel을 이용해서 제목과 X축, Y축의 label도 넣어주었습니다.
plt.scatter('sepal_length', 'sepal_width', data = iris, color = 'green', # marker color alpha = 0.7 # Transparency(0은 투명, 1은 불투명) ) plt.title('Scatter Plot : Iris Sepal', fontsize=15, fontweight = 'bold') plt.xlabel('Sepal Length', fontsize=10) plt.ylabel('Sepal Width', fontsize=10) plt.show()
그룹별로 색상을 지정해주었습니다.
# virginica : red, setosa : green, versicolor : blue iris['color'] = np.where(iris.species == 'virginica', '#ff7979', np.where(iris.species == 'setosa', '#badc58', '#7ed6df')) plt.scatter('sepal_length', 'sepal_width', data = iris, c = iris['color'], # c : color alpha = 0.7 ) plt.title('Scatter Plot : Iris Sepal', fontsize=15, fontweight = 'bold') plt.xlabel('Sepal Length', fontsize=10) plt.ylabel('Sepal Width', fontsize=10) plt.show()
+) 컬러 지정에 사용한 np.where는
np.where(iris.species == 'setosa', 'green', 'blue')
위의 코드를 예로 설명하면
iris.species == 'setosa' 라는 조건에 맞다면 green으로 그렇지 않다면 blue로 변환하겠다는 뜻입니다.
bar plot
barplot을 그리기 앞서 species별 평균을 구하는 데이터를 만들어 주었습니다.
df = iris.groupby('species').mean().reset_index()
기본 barplot을 그려주고,
제목과 X, Y축 label을 지정해주었습니다.
plt.bar(df['species'], # X df['petal_length'] # Y ) plt.title('Bar Plot : Iris Petal Length', fontsize=15, fontweight = 'bold') plt.xlabel('Species', fontsize=10) plt.ylabel('Petal Length', fontsize=10) plt.show()
width와 color 옵션을 이용해서 그래프 막대의 넓이와 컬러를 변경해줄 수 있습니다.
plt.bar(df['species'], df['petal_length'], width = 0.5, color = '#D6A2E8') plt.title('Bar Plot : Iris Petal Length', fontsize=15, fontweight = 'bold') plt.xlabel('Species', fontsize=10) plt.ylabel('Petal Length', fontsize=10) plt.show()
plt.barh는 가로 막대 그래프를 그려줄 수 있습니다.
plt.bar에서 x축, y축 순서였던 것이 y축, x축 순서로 바뀝니다.
label 설정도 그에 맞춰주어야 합니다!
plt.barh(df['species'], # Y df['petal_length'], # X color = '#B33771') plt.title('Bar Plot : Iris Petal Length', fontsize=15, fontweight = 'bold') plt.xlabel('Petal Length', fontsize=10) plt.ylabel('Species', fontsize=10) plt.show()
'Data Science > Data Visualization' 카테고리의 다른 글
[Data Visualization] folium으로 지도에 데이터 시각화하기 (0) 2021.07.25 [Data Visualization] 데이터 시각화 - plotly : Interactive scatter plot (0) 2021.07.13 [Data Visualization] 데이터 시각화 - matplotlib(4) : pie (0) 2021.01.27 [Data Visualization] 데이터 시각화 - matplotlib(3) : hist (0) 2021.01.25 [Data Visualization] 데이터 시각화 - matplotlib(1) (0) 2021.01.18