[참고] 파이썬으로 데이터 시각화하기 (16 ~ 24장)
1. 막대 그래프
plt.bar(years, values, color = 'c', width=0.4)
2. 수평 막대 그래프
plt.barh(years, values, color = 'c', height = 0.3)
3. 산점도 그리기
> s : size / c : color / alpha : 투명도 / cmap : colormap
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
n = 50
x = np.random.rand(n)
y = np.random.rand(n)
area = (30 * np.random.rand(n))**2
colors = np.random.rand(n)
plt.scatter(x, y, s=area, c=colors, alpha=0.5, cmap='Spectral')
plt.colorbar()
plt.show()
4. 히스토그램
> bin : 가로축 구간 개수
> 종류 : histtype = ‘bar’(default), ‘barstacked’, ‘step’, ‘stepfilled’
import matplotlib.pyplot as plt
weight = [68, 81, 64, 56, 78, 74, 61, 77, 66, 68, 59, 71,
80, 59, 67, 81, 69, 73, 69, 74, 70, 65]
plt.hist(weight, bins=10, label='bins=30', color = 'lightblue', histtype = 'bar')
plt.legend()
plt.show()
> 누적 히스토그램
plt.hist(weight, cumulative=True, label='cumulative=True')
plt.hist(weight, cumulative=False, label='cumulative=False')
plt.legend(loc='upper left')
plt.show()
5. 에러바 표시하기
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 5)
y = x**2
yerr = [0.4, 0.8, 0.5, 0.7]
plt.errorbar(x, y + 4, yerr=yerr) # 빨강
plt.errorbar(x, y + 2, yerr=yerr, uplims=True, lolims=True) # 파랑
upperlimits = [True, False, True, False]
lowerlimits = [False, False, True, True]
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits) #보라
plt.show()
6. 파이 차트 그리기
import matplotlib.pyplot as plt
ratio = [34, 32, 16, 18]
labels = ['Apple', 'Banana', 'Melon', 'Grapes']
colors = ['lightblue', 'yellow', 'lightgreen', 'lightgray']
plt.pie(ratio, labels=labels, colors = colors, autopct='%.1f%%', startangle=90, counterclock=False)
plt.show()
8. 박스 플롯
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
data_a = np.random.normal(0, 2.0, 1000)
fig, ax = plt.subplots()
ax.boxplot(data_a)
ax.set_ylim(-10.0, 10.0)
ax.set_xlabel('Data Type')
ax.set_ylabel('Value')
plt.show()
9. 바이올린 플롯
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
data_a = np.random.normal(0, 2.0, 1000)
fig, ax = plt.subplots()
violin = ax.violinplot(data_a)
ax.set_ylim(-10.0, 10.0)
ax.set_xticks([0, 1, 2])
ax.set_xlabel('Data Type')
ax.set_ylabel('Value')
plt.show()
10. 여러개 그래프 넣기
# 그래프 1
plt.subplot(2, 2, 1)
# 그래프 2
plt.subplot(2, 2, 2)
# 그래프 3
plt.subplot(2, 2, 3)
# 그래프 4
plt.subplot(2, 2, 4)
'[스파르타코딩클럽]데이터분석 과정 > PYTHON' 카테고리의 다른 글
[Python][matplotlib](3) 그래프 꾸미기 (0) | 2024.01.20 |
---|---|
[Python][matplotlib] 선 종류, 색깔, 마커표시 기본 정리 (0) | 2024.01.20 |
[python][matplotlib](1) 시각화 기초 세팅 (0) | 2024.01.20 |
[Python 코드카타] 50 ~ 51번 (프로그래머스) (0) | 2024.01.20 |
[Python 코드카타] 47 ~ 49번 (프로그래머스) (1) | 2024.01.19 |