programing

각 하위구에 제목을 추가하는 방법

easyjava 2023. 5. 9. 23:14
반응형

각 하위구에 제목을 추가하는 방법

나는 많은 하위 플롯을 포함하는 하나의 그림을 가지고 있습니다.

fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')

# Returns the Axes instance
ax = fig.add_subplot(311) 
ax2 = fig.add_subplot(312) 
ax3 = fig.add_subplot(313) 

하위 플롯에 제목을 추가하려면 어떻게 해야 합니까?

fig.suptitle모든 그래프에 제목을 추가합니다.ax.set_title()존재합니다. 후자는 하위 플롯에 제목을 추가하지 않습니다.

도와주셔서 고맙습니다.

편집: 수정된 오타 정보set_title()감사합니다, 러트거 케이시스.

ax.title.set_text('My Plot Title')효과도 있는 것 같습니다.

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()

matplotlib:하위 플롯에 제목 추가

ax.set_title()에서는 별도의 하위 플롯에 대한 제목을 설정해야 합니다.

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

이 코드가 당신에게 효과가 있는지 확인해 주시겠습니까?나중에 뭔가 덮어쓰는 게 아닐까요?

다음을 가정한 간단한 대답import matplotlib.pyplot as plt:

plt.gca().set_title('title')

다음과 같이:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

그러면 불필요한 변수가 필요 없습니다.

더 짧게 하려면 다음과 같이 쓸 수 있습니다.

import matplotlib.pyplot as plt
for i in range(4):
    plt.subplot(2,2,i+1).set_title(f'Subplot n°{i+1}')
plt.show()

명확성은 떨어지지만 더 많은 선이나 변수가 필요하지 않습니다.

제가 점점 더 많이 사용하는 솔루션은 다음과 같습니다.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2)  # 1
for i, ax in enumerate(axs.ravel()): # 2
    ax.set_title("Plot #{}".format(i)) # 3
  1. 임의의 축 수 만들기
  2. axs.ravel()은 2차원 객체를 행-주요 스타일의 1차원 벡터로 변환합니다.
  3. 제목을 현재 축-객체에 할당합니다.
fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4,figsize=(11, 7))

grid = plt.GridSpec(2, 2, wspace=0.2, hspace=0.5)

ax1 = plt.subplot(grid[0, 0])
ax2 = plt.subplot(grid[0, 1:])
ax3 = plt.subplot(grid[1, :1])
ax4 = plt.subplot(grid[1, 1:])

ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')

plt.show()

여기에 이미지 설명 입력

여러 개의 이미지가 있는데 이미지를 반복하여 제목과 함께 하나씩 보여주고자 하는 경우 이렇게 할 수 있습니다.ax1, ax2 등을 명시적으로 정의할 필요가 없습니다.

  1. 코드의 라인 1에서와 같이 동적 축(ax)을 정의하고 루프 내에서 제목을 설정할 수 있습니다.
  2. 2D 배열의 행은 축(ax)의 길이(len)입니다.
  3. 각 행에는 두 개의 항목이 있습니다.리스트 내의 리스트입니다(포인트 No.2).
  4. 적절한 축(축) 또는 하위 플롯을 선택한 후 set_subplot을 사용하여 제목을 설정할 수 있습니다.
import matplotlib.pyplot as plt    
fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
for i in range(len(ax)): 
    for j in range(len(ax[i])):
        ## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
        ax[i,j].set_title('Title-' + str(i) + str(j))

반복을 통해서만 모든 그래프에 다른 제목과 레이블을 지정할 수 있습니다.

titles = {221: 'First Plot', 222: 'Second Plot', 223: 'Third Plot', 224: 'Fourth Plot'}
fig = plt.figure()
for x in range(221,225):
  ax = fig.add_subplot(x)
  ax.title.set_text(titles.get(x))

plt.subplots_adjust(left=0.1,
                    bottom=0.1, 
                    right=0.9, 
                    top=0.9, 
                    wspace=0.4, 
                    hspace=0.4)
plt.show()

출력:

여기에 이미지 설명 입력

matplotlib 3.4.3에서 그림.add_subplot 함수는 제목이 다음과 같은 kwarg를 지원합니다.

fig.add_subplot(311, title="first")
fig.add_subplot(312, title="second")

완전성을 위해 다음과 같이 그림 축을 명시적으로 참조하지 않고 요청된 결과를 얻을 수도 있습니다.

import matplotlib.pyplot as plt

plt.subplot(221)
plt.title("Title 1")

plt.subplot(222)
plt.title("Title 2")

plt.subplot(223)
plt.title("Title 3")

plt.subplot(224)
plt.title("Title 4")

여기에 이미지 설명 입력

사용하다plt.tight_layout()레이블이 겹치는 문제가 있는 경우 마지막 그림 뒤에 표시됩니다.

언급URL : https://stackoverflow.com/questions/25239933/how-to-add-a-title-to-each-subplot

반응형