sourcecode

tight_()layout는 피규어 서브타이틀을 고려하지 않습니다.

copyscript 2023. 7. 3. 23:07
반응형

tight_()layout는 피규어 서브타이틀을 고려하지 않습니다.

하면 하위matplotlib이 됩니다.그것을 쉽게 처리할 수 있는 방법을 아는 사람이 있습니까?는 해습니다를 요.tight_layout()하지만 상황을 더 악화시킬 뿐입니다.

예:

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.tight_layout()
plt.show()

다에 하서 지트 조리 있수 다니 습음 에서 하위 할 수 .tight_layout다음과 같이 호출:

fig.tight_layout(rect=[0, 0.03, 1, 0.95])

설명서(https://matplotlib.org/users/tight_layout_guide.html) 에 나와 있습니다.

tight_layout()눈금 레이블, 축 레이블 및 제목만 고려합니다.따라서 다른 아티스트가 잘릴 수도 있고 중복될 수도 마찬가지입니다.

다음을 사용하여 수동으로 간격을 조정할 수 있습니다.plt.subplots_adjust(top=0.85):

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.subplots_adjust(top=0.85)
plt.show()

할 수 한 는 코에서매변쉽경수할있는가입니다.fontsize제목에 사용 중입니다.하지만, 저는 여러분이 단지 그것을 하고 싶어하지 않는다고 가정할 것입니다!

▁using를 하는 것에 대한 몇 대안fig.subplots_adjust(top=0.85):

통보.tight_layout()서로 겹치지 않도록 모든 것을 좋은 위치에 배치하는 데 꽤 능숙합니다. ㅠㅠtight_layout()이 경우 도움이 되지 않는 은 fig.suptitle()을 고려하지 않기 때문입니다.GitHub: https://github.com/matplotlib/matplotlib/issues/829 에서 이 문제에 대한 미해결 문제가 있습니다. [전체 지오메트리 관리자가 필요하여 2014년 폐쇄 - https://github.com/matplotlib/matplotlib/issues/1109 로 이동].

스레드를 , 의, 당문면에대해, 습니이결책한제다는읽를스레드이▁involving▁problem▁if,다니▁to있▁there와 관련된 여러분의 문제에 대한 해결책이 있습니다.GridSpec호출할 때 그림의 맨 위에 공간을 조금 남겨두는 것이 중요합니다.tight_layout 사용rect 문제에 , kwarg가 됩니다. 당신의 문제에 대해, 코드는 다음과 같습니다.

그리드 사양 사용

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

f = np.random.random(100)
g = np.random.random(100)

fig = plt.figure(1)
gs1 = gridspec.GridSpec(1, 2)
ax_list = [fig.add_subplot(ss) for ss in gs1]

ax_list[0].plot(f)
ax_list[0].set_title('Very Long Title 1', fontsize=20)

ax_list[1].plot(g)
ax_list[1].set_title('Very Long Title 2', fontsize=20)

fig.suptitle('Long Suptitle', fontsize=24)    

gs1.tight_layout(fig, rect=[0, 0.03, 1, 0.95])  

plt.show()

결과:

using gridspec

아마도요.GridSpec당신에게 약간 지나친 살인입니다. 그렇지 않으면 당신의 진짜 문제는 훨씬 더 큰 캔버스에 더 많은 하위 플롯을 포함하거나 다른 합병증을 일으킬 것입니다.간단한 해킹은 그냥 사용하는 것입니다.annotate()를 리고좌 잠를니다급표그▁the▁the다로 고정시킵니다.'figure fraction'를 내다suptitle그러나 출력을 확인한 후에는 좀 더 세부적으로 조정해야 할 수도 있습니다.이 두 번째 솔루션은 다음을 사용하지 않습니다.tight_layout().

간단한 솔루션(미세 조정이 필요할 수도 있음)

fig = plt.figure(2)

ax1 = plt.subplot(121)
ax1.plot(f)
ax1.set_title('Very Long Title 1', fontsize=20)

ax2 = plt.subplot(122)
ax2.plot(g)
ax2.set_title('Very Long Title 2', fontsize=20)

# fig.suptitle('Long Suptitle', fontsize=24)
# Instead, do a hack by annotating the first axes with the desired 
# string and set the positioning to 'figure fraction'.
fig.get_axes()[0].annotate('Long Suptitle', (0.5, 0.95), 
                            xycoords='figure fraction', ha='center', 
                            fontsize=24
                            )
plt.show()

결과:

simple

]Python및 2.7.3(64비트) »matplotlib1.2.0]

함께 수 , 촘한레이웃자함은수사없만지할용께과촘막,constrained_layout질문을 참조하십시오. matplotlib에서 많은 하위 플롯을 사용하여 하위 플롯 크기/공간 개선

하위 플롯을 한 번에 추가하는 것이 더 낫다는 것을 알았습니다.

fig, axs = plt.subplots(rows, cols, constrained_layout=True)

# then iterating over the axes to fill in the plots

그러나 그림이 생성되는 시점에 추가할 수도 있습니다.

fig = plt.figure(constrained_layout=True)

ax1 = fig.add_subplot(cols, rows, 1)
# etc

참고: 하위 플롯을 더 가깝게 만들기 위해 사용했습니다.

fig.subplots_adjust(wspace=0.05)

그리고 constrainted_dll은 이것과 함께 작동하지 않습니다 :(

대안적이고 사용하기 쉬운 솔루션은 부제목 호출에서 y 인수를 사용하여 그림에서 부제목 텍스트의 좌표를 조정하는 것입니다(문서 참조).

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', y=1.05, fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.show()

다른 사람들이 언급한 것처럼, 기본적으로 엄격한 레이아웃은 적절한 제목을 고려하지 않습니다.하지만, 저는 그것을 사용하는 것이 가능하다는 것을 알았습니다.bbox_extra_artists고려해야 할 경계 상자로 부제를 전달할 인수:

st = fig.suptitle("My Super Title")
plt.savefig("figure.png", bbox_extra_artists=[st], bbox_inches='tight')

이로 인해 엄격한 레이아웃 계산이 수행됩니다.suptitle당신이 예상하는 것처럼 보입니다.

웹사이트는 저에게 효과적인 예를 들어 이것에 대한 간단한 해결책을 가지고 있습니다.제목에 대한 실제 공백을 남기는 코드 행은 다음과 같습니다.

plt.tight_layout(rect=[0, 0, 1, 0.95]) 

다음은 저에게 효과가 있었다는 증거 이미지입니다.

v3.3 기준 tight_layout 이제지를 지원합니다.suptitle:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 3)
for i, ax in enumerate(axs):
    ax.plot([1, 2, 3])
    ax.set_title(f'Axes {i}')

fig.suptitle('suptitle')
fig.tight_layout()

enter image description here

저는 매트플롯립 트리밍 방법에 어려움을 겪었기 때문에 이제 막 이것을 하는 기능을 만들었습니다.bash로 불러들입니다.ImageMagick잘 작동하고 피규어 가장자리에서 여분의 공백을 모두 제거하는 모그리피 명령.이렇게 하려면 UNIX/Linux를 사용하고 있어야 합니다.bash껍질을 벗기고, 가지고 있습니다.ImageMagick설치된.

당신의 일이 끝난 후에 여기로 전화하세요.savefig()콜.콜.

def autocrop_img(filename):
    '''Call ImageMagick mogrify from bash to autocrop image'''
    import subprocess
    import os

    cwd, img_name = os.path.split(filename)

    bashcmd = 'mogrify -trim %s' % img_name
    process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)

제게 유일하게 효과가 있었던 것은 통화를 자막으로 수정하는 것이었습니다.

fig.suptitle("title", y=.995)

사용할 때 발생한 유사한 문제가 있었습니다.tight_layout매우 큰 그리드의 플롯(200개 이상의 하위 플롯)과 주피터 노트북의 렌더링에 사용됩니다.나는 항상 당신의 것을 배치하는 빠른 해결책을 만들었습니다.suptitle상단 하위 그림 위의 특정 거리에서:

import matplotlib.pyplot as plt

n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)

#make plots ...

# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)

가변 크기의 부분구의 경우에도 이 방법을 사용하여 맨 위의 부분구 맨 위를 가져온 다음 부분구 제목에 추가할 양을 수동으로 정의할 수 있습니다.

언급URL : https://stackoverflow.com/questions/8248467/tight-layout-doesnt-take-into-account-figure-suptitle

반응형