Python | Matplotlib

Jihun Kim·2021년 9월 3일
0

파이썬

목록 보기
6/11

♟ Matplotlib

  • 그래프를 그릴 수 있는 파이썬 라이브러리
import matplotlib.pyplot as plt

x = [i for i in range(1, 6)]
y = [i for i in range(1, 6)]

plt.plot(x, y)
plt.title("First Plot")
plt.xlabel("x")
plt.ylabel("y")

객체 기반 스타일로 그래프 그리기 🥊

  • object-oriented interface
    👉 fig는 전체 도화지를 의미함
    👉 ax는 그래프를 그릴 수 있는곳
import matplotlib.pyplot as plt

x = [i for i in range(1, 6)]
y = [i for i in range(1, 6)]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('First plot")
ax.set_xlabel("x")
ax.set_ylabel("y")

fig.set_dpi(300)  
# dot per inch의 약자(그래프가 크게 저장됨)
# 저화질로 저장시 숫자를 낮추면 됨

fig.savefig("first_plot.png")  # 현재 디렉토리에 저장됨

여러개의 그래프 그리기

# linspace(시작, 끝, 구간)
x = np.linspace(0, np.pi * 4, 100)
# 2 : 세로 축으로 0, 1 두 개의 데이터를 갖게 됨
fig, axes = plt.subplots(2, 1)
axes[0].plot(x, np.sin(x))  # 위의 그래프
axes[1].plot(x, np.cos(x))  # 아래 그래프

Matplotlib의 그래프들 🚣‍♀️

1. Line plot

fig, ax = plt.subplots()
x = np.arange(15)
y = x ** 2
ax.plot(
	x, y,
    linestyle=":",
    marker="*",
    color="#524FA1"
)

⚡ linestyle

ax.plot(x, y, linestyle="-")  # solid
ax.plot(x, y, linestyle="--")  # dashed
ax.plot(x, y, linestyle="-.")  # dashdot
ax.plot(x, y, linestyle=":")  # dotted

⚡ Marker

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="*")  

2. Scatter plot

  • plot의 세 번째 인자에 'marker' 값을 주어서 변경한다.
fig, ax = plt.subplots()
x = np.arange(10)
y = x ** 2
ax.plot(
	x, y,
    "o",
    markersize=15,
    markerfacecolor='white',
    markeredgecolor='blue'
)
  • 각 점의 색 다르게 표현하기
fig, ax = plt.subplots()
x = np.random.randn(50)
x = np.random.randn(50)
colors = np.random.randint(0, 100, 50)  # marker가 전부 다른 색을 갖게 해준다.
sizes = 500 * np.pi * np.random.randn(50) ** 2
ax.scatter(x, y, c=colors, s=sizes, alpha=0.3)  # alpha는 투명도

3. Bar plot

x = np.arange(10)
fig, ax = plt.subplots(figsize=(12, 4))  # 가로 12, 세로 4
ax.bar(x, x**2)
  • 데이터 축적해서 bar plot 그리기(누적된 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:
  # bottom을 지정해서 해당 지점부터 다시 데이터를 쌓아 올린다.
  ax.bar(x_ax, data[i], bottom=np.sum(data[:i], axis=0))
ax.set_xticks(x_ax)
ax.set_xticklabels(['A', 'B', 'C'])

4. Histogram

fig, ax = plt.subplots()
data = np.random.randn(1000)
ax.hist(data, bins=50)  # 막대기가 50개 생김

축 경계 조정하기

  • 그래프가 보이는 지점을 지정하는 것
x = np.linspace(0, 10, 1000)  # 0~10 사이의 1000개 데이터
fig, ax = plt.subplots()
ax.plot(x, np.sin(x))
ax.set_xlim(-2, 12)  # x축이 시작하고 끝나는 지점 설정
ax.set_ylim(-1.5, 1.5)  # y축이 시작하고 끝나는 지점 설정

범례

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',  # 위치 : lower, center도 있음
	shadow=True,
    fancybox=True,  # 모서리 둥글게
    borderpad=2  # 박스의 padding 같은 것
)

Matplotlib with pandas 🏋️‍♂️

  • pandas로 가져온 dataframe을 그래프로 그리기
fig, ax = plt.subplots()
ax.plot(df['order'], df['height(cm)'], label='height')
ax.set_xlabel('order')
ax.set_ylabel('height(cm)')

🐧 이 글은 엘리스 AI 트랙 과정 중 '실전 데이터 분석' 강의 내용을 바탕으로 작성 되었습니다.

profile
쿄쿄

0개의 댓글