programing

모든 하위 플롯 위에 단일 주 제목을 설정하는 방법

telecom 2023. 6. 29. 19:48
반응형

모든 하위 플롯 위에 단일 주 제목을 설정하는 방법

사용 중pyplot저는 4개의 하위 플롯을 가지고 있습니다.모든 하위 플롯 위에 단일 메인 타이틀을 설정하는 방법은 무엇입니까? title()마지막 하위 플롯 위에 설정합니다.

사용 또는:

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)        
    ax.imshow(data)

fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()

enter image description here

이것을 자신의 그림에 적용할 때 유용한 몇 가지 사항:

  • 저는 사용의 일관성을 선호합니다.fig.suptitle(title)보다는plt.suptitle(title)
  • 사용 시fig.tight_layout()제목을 다음으로 이동해야 합니다.fig.subplots_adjust(top=0.88)
  • 글꼴 크기에 대한 아래 답변 참조

matplotlib 문서의 하위 플롯 데모에서 가져온 마스터 제목으로 조정된 코드 예제.

A nice 4x4 plot

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)

axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')

# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)

plt.show()

하위 플롯에도 제목이 있는 경우 주 제목 크기를 조정해야 할 수 있습니다.

plt.suptitle("Main Title", size=16)

언급URL : https://stackoverflow.com/questions/7066121/how-to-set-a-single-main-title-above-all-the-subplots

반응형