subplot titles - 서브플롯 제목 설정

1. subplot 각 plot에 제목 설정

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3,3,100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 1/(1+np.exp(-x))
y4 = np.exp(x)

fig, ax = plt.subplots(2, 2)
  • 방법 1 : ax.set_title()

1-1)

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)

ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")

fig.tight_layout()
plt.show()

1-2)

i=0
for a in range(len(ax)): 
    for b in range(len(ax[a])):
        ax[a, b].plot(x, y[i])
        subplot_title=("Subplot"+str(i))
        ax[a,b].set_title(subplot_title)
        i=i+1

figure.tight_layout()
plt.show()
  • 방법 2 : ax.title.set_text()
ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)

ax[0, 0].title.set_text("Sine function")
ax[0, 1].title.set_text("Cosine function")
ax[1, 0].title.set_text("Sigmoid function")
ax[1, 1].title.set_text("Exponential function")

fig.tight_layout()
plt.show()
  • 방법 3 : plt.gca()
import matplotlib.pyplot as plt
plt.subplots(2, 2) 
x = [1, 2, 3]
y = [2, 4, 6]

3-1) plt.gca().set_title()

for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.plot(x, y)
    plt.gca().set_title('Title-' + str(i))

plt.show()

plt.tight_layout()

3-2) plt.gca().title.set_text()

for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.plot(x, y)
    plt.gca().title.set_text('Title-' + str(i))

plt.show()

plt.tight_layout()

2. subplot 전체 제목 설정

import numpy as np
import matplotlib.pyplot as plt

m1=1
c1=0

m2 = 2
c2 = 2

m3 = 2
c3 = 1

m4 = 1
c4 = 2

x=np.linspace(0,3,100)
y1 = m1*x + c1
y2 = m2*x + c2
y3 = m3*x + c3
y4 = m4*x + c4

fig, ax = plt.subplots(2, 2,figsize=(10, 8))

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)

ax[0, 0].set_title("Line-1")
ax[0, 1].set_title("Line-2")
ax[1, 0].set_title("Line-3")
ax[1, 1].set_title("Line-4")
  • 방법 1 : plt.suptitle()
plt.suptitle('Various Straight Lines',fontsize=20)

fig.tight_layout()
plt.show()
  • 방법 2 : fig.suptitle()
fig.suptitle('Various Straight Lines',fontweight ="bold") 

fig.tight_layout()
plt.show()

3. 공식사이트 참고자료

https://matplotlib.org/stable/gallery/subplots_axes_and_figures/figure_title.html

좋은 웹페이지 즐겨찾기