Development Tip

Python을 사용하여 plt.show () 창을 최대화하는 방법

yourdevel 2020. 10. 30. 21:08
반응형

Python을 사용하여 plt.show () 창을 최대화하는 방법


호기심을 위해 아래 코드에서이 작업을 수행하는 방법을 알고 싶습니다. 나는 답을 찾고 있었지만 쓸모가 없습니다.

import numpy as np
import matplotlib.pyplot as plt
data=np.random.exponential(scale=180, size=10000)
print ('el valor medio de la distribucion exponencial es: ')
print np.average(data)
plt.hist(data,bins=len(data)**0.5,normed=True, cumulative=True, facecolor='red', label='datos tamano paqutes acumulativa', alpha=0.5)
plt.legend()
plt.xlabel('algo')
plt.ylabel('algo')
plt.grid()
plt.show()

나는 보통 사용

mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)

를 호출하기 전에 plt.show()창이 최대화됩니다. 이것은 'wx'백엔드에서만 작동합니다.

편집하다:

Qt4Agg 백엔드의 경우 kwerenda의 답변을 참조하십시오 .


나는 평판이 제로이기 때문에 Python 2.7.5 및 Matplotlib 1.3.1을 실행하는 Windows (WIN7)에 새로운 답변 외에 다른 표시를 남길 수 없습니다.

다음 줄을 사용하여 TkAgg, QT4Agg 및 wxAgg에 대한 Figure 창을 최대화 할 수있었습니다.

from matplotlib import pyplot as plt

### for 'TkAgg' backend
plt.figure(1)
plt.switch_backend('TkAgg') #TkAgg (instead Qt4Agg)
print '#1 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
### works on Ubuntu??? >> did NOT working on windows
# mng.resize(*mng.window.maxsize())
mng.window.state('zoomed') #works fine on Windows!
plt.show() #close the figure to run the next section

### for 'wxAgg' backend
plt.figure(2)
plt.switch_backend('wxAgg')
print '#2 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)
plt.show() #close the figure to run the next section

### for 'Qt4Agg' backend
plt.figure(3)
plt.switch_backend('QT4Agg') #default on my system
print '#3 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()

작업 예제 (최소한 Windows의 경우)에 결합 된 이전 답변 (및 일부 추가 사항)에 대한 요약이 도움이되기를 바랍니다. 건배


Qt 백엔드 (FigureManagerQT)에서 적절한 명령은 다음과 같습니다.

figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()

이렇게하면 TkAgg 백엔드가있는 Ubuntu 12.04에서 창이 전체 화면을 차지하게됩니다.

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())

나를 위해 위의 어떤 것도 효과가 없었습니다. matplotlib 1.3.1이 포함 된 Ubuntu 14.04에서 Tk 백엔드를 사용합니다.

다음 코드는 최대화와 동일하지는 않지만 내 목적에 잘 맞는 전체 화면 플롯 창을 만듭니다.

from matplotlib import pyplot as plt
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()

이것은 작동합니다 ( 적어도 TkAgg에서는) :

wm = plt.get_current_fig_manager()
wm.window.state('zoomed')

(위에서 채택하고 Tkinter를 사용하여 창을 눈에 띄게 확대하지 않고 사용 가능한 화면 크기를 얻을 수있는 방법이 있습니까? )


나도 얻는다 mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame'.

그런 다음 속성 mng살펴 보았고 다음을 발견했습니다.

mng.window.showMaximized()

그것은 나를 위해 일했습니다.

그래서 같은 문제가있는 사람들을 위해 이것을 시도 할 수 있습니다.

그건 그렇고, 내 Matplotlib 버전은 1.3.1입니다.


우분투에서 전체 화면 모드로 이것을 찾았습니다.

#Show full screen
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()

이것은 일종의 해키이며 아마도 휴대가 불가능할 것입니다. 빠르고 더러운 것을 찾는 경우에만 사용하십시오. 화면보다 훨씬 크게 설정하면 화면 전체를 정확하게 차지합니다.

fig = figure(figsize=(80, 60))

사실 Qt4Agg가있는 Ubuntu 16.04에서는 화면보다 크면 창 (전체 화면이 아님)을 최대화합니다. (두 개의 모니터가있는 경우 하나에서 최대화합니다.)


시도 plt.figure(figsize=(6*3.13,4*3.13))플롯 더 크게 만들 수 있습니다.


플롯에 초점이 맞춰진 상태에서 f키 (또는 ctrl+f1.2rc1)를 누르면 플롯 창이 전체 화면으로 표시됩니다. 최대화는 아니지만 아마도 더 좋습니다.

그 외에 실제로 최대화하려면 GUI 툴킷 특정 명령을 사용해야합니다 (특정 백엔드에 대해 존재하는 경우).

HTH


내 버전 (Python 3.6, Eclipse, Windows 7)에서는 위에 제공된 스 니펫이 작동하지 않았지만 Eclipse / pydev (입력 후 : mng.)에서 제공 한 힌트를 사용하여 다음을 발견했습니다.

mng.full_screen_toggle()

mng-commands를 사용하는 것은 로컬 개발에만 괜찮은 것 같습니다 ...


추가 키워드 인수와 함께 'Figure.set_size_inches'메서드를 사용해보십시오 forward=True. 에 따르면 문서 , 이것은 해야 그림 창 크기를 조정합니다.

실제로 발생 하는지 여부 는 사용중인 운영 체제에 따라 다릅니다.


좋아, 이것이 나를 위해 일한 것입니다. 나는 전체 showMaximize () 옵션을 수행했고 그림의 크기에 비례하여 창 크기를 조정하지만 캔버스를 확장하고 '맞추지'않습니다. 나는 이것을 다음과 같이 해결했다.

mng = plt.get_current_fig_manager()                                         
mng.window.showMaximized()
plt.tight_layout()    
plt.savefig('Images/SAVES_PIC_AS_PDF.pdf') 

plt.show()

Win 10에서 완벽하게 작동 한 유일한 솔루션입니다.

import matplotlib.pyplot as plt

plt.plot(x_data, y_data)

mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.show()

My best effort so far, supporting different backends:

from platform import system
def plt_maximize():
    # See discussion: https://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window-using-python
    backend = plt.get_backend()
    cfm = plt.get_current_fig_manager()
    if backend == "wxAgg":
        cfm.frame.Maximize(True)
    elif backend == "TkAgg":
        if system() == "win32":
            cfm.window.state('zoomed')  # This is windows only
        else:
            cfm.resize(*cfm.window.maxsize())
    elif backend == 'QT4Agg':
        cfm.window.showMaximized()
    elif callable(getattr(cfm, "full_screen_toggle", None)):
        if not getattr(cfm, "flag_is_max", None):
            cfm.full_screen_toggle()
            cfm.flag_is_max = True
    else:
        raise RuntimeError("plt_maximize() is not implemented for current backend:", backend)

This doesn't necessarily maximize your window, but it does resize your window in proportion to the size of the figure:

from matplotlib import pyplot as plt
F = gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True)#Set forward to True to resize window along with plot in figure.
plt.show() #or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html


The following may work with all the backends, but I tested it only on QT:

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

plt.switch_backend('QT4Agg') #default on my system
print('Backend: {}'.format(plt.get_backend()))

fig = plt.figure()
ax = fig.add_axes([0,0, 1,1])
ax.axis([0,10, 0,10])
ax.plot(5, 5, 'ro')

mng = plt._pylab_helpers.Gcf.figs.get(fig.number, None)

mng.window.showMaximized() #maximize the figure
time.sleep(3)
mng.window.showMinimized() #minimize the figure
time.sleep(3)
mng.window.showNormal() #normal figure
time.sleep(3)
mng.window.hide() #hide the figure
time.sleep(3)
fig.show() #show the previously hidden figure

ax.plot(6,6, 'bo') #just to check that everything is ok
plt.show()

Here is a function based on @Pythonio's answer. I encapsulate it into a function that automatically detects which backend is it using and do the corresponding actions.

def plt_set_fullscreen():
    backend = str(plt.get_backend())
    mgr = plt.get_current_fig_manager()
    if backend == 'TkAgg':
        if os.name == 'nt':
            mgr.window.state('zoomed')
        else:
            mgr.resize(*mgr.window.maxsize())
    elif backend == 'wxAgg':
        mgr.frame.Maximize(True)
    elif backend == 'Qt4Agg':
        mgr.window.showMaximized()

참고URL : https://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window-using-python

반응형