programing

plt.show() 창을 최대화하는 방법

instargram 2023. 9. 4. 19:32
반응형

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()

저는 Python 2.7.5 & Matplotlib 1.3.1을 실행하는 Windows(WIN7)에 있습니다.

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

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()

사용할 수 있는 여러 수치를 최대화하려면

for fig in figs:
    mng = fig.canvas.manager
    # ...

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

Qt 백엔드 사용(FigureManager)QT) 적절한 명령은 다음과 같습니다.

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

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

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

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

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

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

나에게는 위의 것들 중 아무것도 효과가 없었습니다.저는 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()

주로 사용합니다.

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

전화하기 plt.show()최대화된 창을 얻을 수 있습니다.이것은 'wx' 백엔드에서만 작동합니다.

편집:

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

다양한 백엔드를 지원하는 지금까지의 최선의 노력:

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() == "Windows":
            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)

알겠습니다mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame'뿐만 아니라.

그리고 나서 그 속성들을 살펴봤습니다.mng그리고 나는 이것을 발견했습니다:

mng.window.showMaximized()

그것은 저에게 효과가 있었습니다.

그래서 같은 문제를 가진 사람들은 이것을 시도해 볼 수 있습니다.

참고로 제 Matplotlib 버전은 1.3.1입니다.

이것은 좀 구식이고 아마도 휴대용이 아닐 것입니다. 빠르고 더러운 것을 찾고 있을 때만 사용하세요.수치를 화면보다 훨씬 크게 설정하면 정확히 전체 화면이 필요합니다.

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

실제로 Qt4Agg가 탑재된 Ubuntu 16.04에서는 화면보다 큰 경우 창(전체 화면이 아님)을 최대화합니다. (모니터가 두 개인 경우에는 그 중 하나에서 최대화합니다.)

Ubuntu에서 전체 화면 모드용으로 찾았습니다.

#Show full screen
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
import matplotlib.pyplot as plt
def maximize():
    plot_backend = plt.get_backend()
    mng = plt.get_current_fig_manager()
    if plot_backend == 'TkAgg':
        mng.resize(*mng.window.maxsize())
    elif plot_backend == 'wxAgg':
        mng.frame.Maximize(True)
    elif plot_backend == 'Qt4Agg':
        mng.window.showMaximized()

다음 함수를 합니다.maximize() 앞에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()

백엔드 GTK3Agg의 경우,maximize()특히 소문자 m:

manager = plt.get_current_fig_manager()
manager.window.maximize()

Ubuntu 20.04에서 Python 3.8로 테스트되었습니다.

.f 키(으)로 표시)ctrl+f 1에서는 플롯에 을 맞추면 창이 으로 표시됩니다.1.2rc1)에서는 플롯 창이 표시됩니다.그다지 극대화되지는 않았지만, 아마도 더 나을 것입니다.

이 외에도 실제로 최대화하려면 GUI Toolkit 관련 명령을 사용해야 합니다(특정 백엔드용으로 존재하는 경우).

HTH

여기 @Pythonio의 답변을 기반으로 한 기능이 있습니다.사용 중인 백엔드를 자동으로 감지하여 해당 작업을 수행하는 기능으로 캡슐화합니다.

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()

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

mng.full_screen_toggle()

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

'을 사용해 . 키워드 인수 set_size_sigue' (인수 set_size_sigue')forward=True설명서에 따르면 그림 창 크기가 조정됩니다.

실제로 이러한 현상이 발생하는지 여부는 사용 중인 운영 체제에 따라 달라집니다.

ㅠㅠplt.figure(figsize=(6*3.13,4*3.13))그림을 확대할 수 있습니다.

이것이 저에게 효과가 있었던 것입니다.전체 showMaximize() 옵션을 실행했는데 그림 크기에 비례하여 창 크기를 조정하지만 캔버스를 확장하거나 '맞추지 않습니다.이 문제를 해결한 방법:

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

plt.show()

Tk 기반 백엔드(TkAgg)의 경우 다음 두 가지 옵션이 창을 최대화하고 전체 화면을 표시합니다.

plt.get_current_fig_manager().window.state('zoomed')
plt.get_current_fig_manager().window.attributes('-fullscreen', True)

여러 창에 플롯할 때는 각 창에 대해 다음과 같이 기록해야 합니다.

data = rasterio.open(filepath)

blue, green, red, nir = data.read()
plt.figure(1)
plt.subplot(121); plt.imshow(blue);
plt.subplot(122); plt.imshow(red);
plt.get_current_fig_manager().window.state('zoomed')

rgb = np.dstack((red, green, blue))
nrg = np.dstack((nir, red, green))
plt.figure(2)
plt.subplot(121); plt.imshow(rgb);
plt.subplot(122); plt.imshow(nrg);
plt.get_current_fig_manager().window.state('zoomed')

plt.show()

여기서 두 '그림'은 별도의 창에 표시됩니다.다음과 같은 변수 사용

figure_manager = plt.get_current_fig_manager()

변수가 여전히 첫 번째 창을 참조하기 때문에 두 번째 창을 최대화하지 못할 수 있습니다.

저는 같은 일을 성취하기 위해 노력할 때 제가 보고 있던 스레드에서 몇 가지 답을 모았습니다.이 기능은 모든 플롯을 최대화하고 사용 중인 백엔드에 대해 별로 신경 쓰지 않는 기능입니다.저는 대본의 마지막에 실행합니다.멀티스크린 설정을 사용하는 다른 사용자가 언급한 문제가 여전히 발생합니다. 이 경우 fm.window.max size()는 현재 모니터의 크기가 아닌 전체 화면 크기를 가져옵니다.원하는 화면 크기를 알고 있으면 *fm.window.max size()를 튜플(width_inch, height_inch)로 바꿀 수 있습니다.

기능적으로 이 모든 작업은 그림 목록을 가져와서 현재 최대 창 크기에 대한 현재 해석을 자유롭게 할 수 있도록 크기를 조정하는 것입니다.

def maximizeAllFigures():
    '''
    Maximizes all matplotlib plots.
    '''
    for i in plt.get_fignums():
        plt.figure(i)
        fm = plt.get_current_fig_manager()
        fm.resize(*fm.window.maxsize())

위의 대부분의 솔루션을 사용해 보았지만 Python 3.10.5가 설치된 Windows 10에서 제대로 작동하는 솔루션은 없습니다.

아래는 제 쪽에서 완벽하게 작동하는 것을 발견한 것입니다.

import ctypes

mng = plt.get_current_fig_manager()
mng.resize(ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))

이렇게 하면 창이 최대화되는 것은 아니지만 그림 크기에 비례하여 창 크기가 조정됩니다.

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

http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html 에서도 도움이 될 수 있습니다.

다음은 모든 백엔드에서 작동할 수 있지만 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()

언급URL : https://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window

반응형