공부 기록/파이썬
Matplotlib 데이터 시각화
용재
2021. 11. 12. 23:41
Matploblib 그래프
Line Plot
fig, ax = plt.subplots()
x = np.arange(15)
y = x ** 2
ax.plot( x, y,
linestyle = ":", # 점선
marker = "*", # 좌표들이 *로 표시
color = "#524FA1" )
# x = 0 ~ 14, y = x^2의 그래프
Line style
x = np.arange(10)
fig, ax = plt.subplots()
ax.plot(x, x, linestyle="-")
# solid
ax.plot(x, x+2, linestyle = "--")
# dashed
ax.plot(x, x+4, linestyle = "-.")
# dashdot
ax.plot(x, x+6, linestyle = ":")
#dotted
Color
x = np.arange(10)
fig, ax = plt.subplots()
ax.plot(x, x, color = 'r')
ax.plot(x, x+2, color = 'green')
ax.plot(x, x+4, color = "0.8")
ax.plot(x, x+6, color = '#524FA1')
Marker
x = np.arange(10)
fig, ax = subplots()
ax.plot(x, x, marker = ".")
ax.plot(x, x+2, marker = "o")
ax.plot(x, x+4, marker = "v")
ax.plot(x, x+6, marker = "s")
ax.plot(x, x+8, marker = "*")
축 경계 조정하기
x = np.linespace(0, 10, 1000) # (start, end, step)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x)) # sin(x)의 그래프
ax.set_xlim(-2, 12) # x축이 -2부터 12까지
ax.set_ylim(-1.5, 1.5) # y축이 -1.5부터 1.5까지
범례
x = np.arange(10)
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) # 보더 패드의 크기
Bar & Histogram
Bar plot
# bar
x = np.arange(10) # x = 0 ~ 9
fig, ax = plt.subplots(gidsize = (12, 4)) # 가로 : 12, 세로 : 4
ax.bar(x, x*2) # y = 2x
누적된 Bar plot
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_ax:
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) # data의 개수 : 1000
ax.hist(data, bins=50) # bins : 막대의 개수
Matplotlib with pandas
df = pd.read_csv("./president_heights.csv")
fig, ax = plt.subplots()
ax.plot(df["order"], df["height(cm)"], label = "height")
ax.set_xlabel("order")
ax.set_ylabel("height(cm)")
df = pd.read_csv("./data/pokemnon.csv")
fire = df[(df['Type 1'] == 'Fire') | ((df['Type2']) == "Fire")]
# Type1 이나 Type2 중 하나가 불 속성인 포켓몬
water = df[(df['Type 1'] == 'Water') | ((df['Type2']) == "Water")]
# Type1 이나 Type2 중 하나가 물 속성인 포켓몬
fig, ax = plt.subplots()
ax.scatter(fire['Attack'], fire['Defense'], color = 'R', label= 'Fire', marker = "*", s = 50)
ax.scatter(water['Attack'], water['Defense'], color = 'B', label= 'Water', marker = "*", s = 25)
ax.set_xlabel("Attack")
ax.set_ylabel("Defense" ax.legend(loc = "upper right")