보리차
07) Matplotlib 데이터 시각화 본문
Matplotlib
파이썬에서 데이터를 그래프나 차트로 시각화 할 수 있는 라이브러리
그래프 그려보기
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
plt.plot(x, y)
plt.title("First Plot") # 그래프 타이틀
plt.xlabel("x") # x축
plt.ylabel("y") # y축
# 오브젝트 오리엔티드 인터페이스?
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("First Plot") # 그래프 타이틀
ax.set_xlabel("x") # x축
ax.set_ylabel("y") # y축
저장하기
fig, ax = plt.subplots()
ax.plot(x, y)
fig.set_dpi(300) # fig는 전체 도화지, ax는 그 위에 그려지는 그래프
fig.savefig("first_plot.png")
여러개의 그래프 그리기
x = np.linspace(0, np.pi*4, 100)
fig, axes = plt.subplots(2, 1) # 2x1 크기의 도화지 fig 생성
axes[0].plot(x, np.sin(x))
axes[1].plot(x, np.cos(x))
matplotlib 그래프들
Line plot
# Line plot
fig, ax = plt.subPlots()
ax.plot(x, y,
linestyle=":",
marker="*",
color="#524FA1"
)
그래프 옵션
# Line style
# solid
ax.plot(x, x, linestyle="-")
# dashed
ax.plot(x, x, linestyle="--")
# dashdot
ax.plot(x, x, linestyle="-.")
# dotted
ax.plot(x, x, linestyle=":")
# color
ax.plot(x, x, color="r") # 축약어
ax.plot(x, x, color="green")
ax.plot(x, x, color="0.8") # grayscale
ax.plot(x, x, color="#524FA1") # RGB코드
# Marker
ax.plot(x, x, marker=".")
ax.plot(x, x, marker="o") # 원
ax.plot(x, x, marker="v") # 삼각형
ax.plot(x, x, marker="s") # 사각형
ax.plot(x, x, marker="*")
축 경계 조정하기
fig, ax = plt.subplots()
ax.plot(x, np.sin(x))
# x, y 값의 범위 지정 가능
ax.set_xlim(-2, 12)
ax.set_ylim(-1.5, 1.5)
범례
fig, ax = plt.subplots()
ax.plot(x, x, label='y=x')
ax.plot(x, x**2, label='y=x^2')
ax.set_xlabel("x")
ax.set_ylabel("y")
# 범례 지정
ax.legend(
loc="upper right",
shadow=True,
fancybox=True,
borderpad=2
)
Scatter
# 산점도
ax.plot(
x, x**2, "o", # 세 번째 값에 마커를 지정하면 라인이 아니라 점으로 그림
markersize=15,
markerfacecolor="white",
markeredgecolor="blue"
)
# 사이즈와 컬러를 각각 지정해서 만들 수 있다.
colors = np.random.randint(0, 100, 50)
sizes = 500 * np.pi * np.random.rand(50) ** 2
ax.scatter(
x, y, c=colors, s=sizes, alpha=0.3 # alpha: 투명도
)
Bar plot
fig, ax = plt.subplots(figsize=(12, 4))
ax.bar(x, x*2)
# 누적해서 그릴 수 있다.
x = np.random.rand(3)
y = np.random.rand(3)
z = np.random.rand(3)
data = [x, y, z]
fig, ax = plt.subplots()
x_ax = np.arange(3)
for i in x_xa:
ax.bar(x_ax, data[i],
bottom=np.sum(data[:i], axis=0)) # 바닥값을 이전까지의 합으로
ax.set_xticks(x_ax)
ax.set_xticklabels(['A', 'B', 'C'])
Histogram
fig, ax = plt.subplots()
data = np.random.randn(1000)
ax.hist(data, bins=50) # bins: 막대기 갯수
Matplotlib with pandas
df = pd.read_csv("filename.csv")
fig, ax = plt.subplots()
ax.plot(dt["order"], df["height(cm)"], label="height")
ax.set_xlabel("order")
ax.set_ylabel("height(cm)")
'공부 > 데이터 분석' 카테고리의 다른 글
06) Pandas 심화 (0) | 2021.09.05 |
---|---|
05) Pandas (0) | 2021.09.03 |
04) NumPy (0) | 2021.09.02 |
03) 복잡한 형태의 데이터: csv, lambda, map, filter (0) | 2021.08.31 |
02) 데이터형 변환 - 딕셔너리, JSON, 집합, matplotlib (0) | 2021.08.31 |