How to maximize a plt.show() window
Asked Answered
K

24

155

Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless.

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()
Karmakarmadharaya answered 15/9, 2012 at 17:31 Comment(3)
Tip for Windows: the only that worked for me was plt.get_current_fig_manager().window.state('zoomed').Gombosi
mng = plt.get_current_fig_manager() mng.window.maximize()Perrone
plt.get_current_fig_manager().window.showMaximized() worksPhene
S
46

I usually use

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

before the call to plt.show(), and I get a maximized window. This works for the 'wx' backend only.

EDIT:

for Qt4Agg backend, see kwerenda's answer.

Succinctorium answered 26/9, 2012 at 9:53 Comment(8)
Using this, I get mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame' in Matplotlib 1.2.0Romish
It works with backend wx, I've updated the post accordingly. Likely the Tk backend you are using doesn't support this feature. Do you have the option to change matplotlib backend to 'wx'?Succinctorium
error on mac: mng.frame.Maximize(True) AttributeError: 'FigureManagerMac' object has no attribute 'frame'Heterosexuality
Is there a known solution to do this on the MacOSXbackend? The FigureManagerMac seems to have neither the attribute windownor frame.Haerr
I have the same issue on WindowsIllsuited
the OO interface: fig, ax = plt.subplots(1, 1) fig.canvas.manager.window.showMaximized() works in Qt5, couldn't get the 'WX' work on my machineBuseck
Similar error, like first comment. AttributeError: 'FigureManagerQT' object has no attribute 'frame'.Pearlinepearlman
Same issue on Ubuntu: mng.frame.Maximize(True) AttributeError: 'FigureManagerTk' object has no attribute 'frame'Seigniory
U
208

I am on a Windows (WIN7), running Python 2.7.5 & Matplotlib 1.3.1.

I was able to maximize Figure windows for TkAgg, QT4Agg, and wxAgg using the following lines:

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

if you want to maximize multiple figures you can use

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

Hope this summary of the previous answers (and some additions) combined in a working example (at least for windows) helps.

Unpretentious answered 15/3, 2014 at 1:12 Comment(9)
### works on Ubuntu??? >> did NOT working on windows mng.resize(*mng.window.maxsize()) #works perfect on linux for meRemmer
@Daniele, your solution works for me on TkAgg on Ubuntu. Thanks! But it took me a while to parse ;) Maybe get rid of everything before "mng.resize...".Eduction
Is there an easy way to check what backend you are using? kinda used trial end error now.Thais
Unfortunately, I tried your code with Qt5Agg, when I type in figManager.window.showMaximized(), the maximized fullscreen window just poped up. The next line: plt.show() just show another window which plots the data in a normal size window.Subcortex
The Tk based solution does not work for me: _tkinter.TclError: bad argument "zoomed": must be normal, iconic, or withdrawn (Ubuntu 16.04).Styles
On my Ubuntu (16.04) machine I use mng = plt.get_current_fig_manager() mng.full_screen_toggle()Ruttger
The Qt4Agg solution works for me using Cygwin, with Qt5.Soapsuds
Worked for me (Python 3.6.5, TkInter, Windows 10)Aun
On my Mint 20.2 mng.window.showMaximized() worked just fine, thanks.Theft
S
107

With Qt backend (FigureManagerQT) proper command is:

figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
Soliz answered 16/9, 2013 at 9:39 Comment(6)
This still requires plt.show() afterwards. Great answer though, works on windows!Stephanestephani
'_tkinter.tkapp' object has bi attribute 'showMaximized'. Always more convinced that Python is a joke more than a languageJinni
@Jinni First, this is for Qt4, not Tk. Second, you're blaming a language for what is an external package design issue. You can have this kind of issue in any language.Soapsuds
I get AttributeError: '_tkinter.tkapp' object has no attribute 'showMaximized' on Windows.Gombosi
Works with the PyQt5 backend for me.Scorpius
Note that if you do a savefig command directly after the maximization of the plot, then the stored image wont be in full screen. Add a plt.pause(1) to it to make sure that the operation was performed succesfullyCicelycicenia
H
57

This makes the window take up the full screen for me, under Ubuntu 12.04 with the TkAgg backend:

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())
Hosea answered 26/1, 2013 at 13:10 Comment(6)
Note that this has weird effects on a multiple monitors setup. The window will use up all monitors, instead of being maximized.Fahlband
This will not create a maximized window (which should snap to the edges of the screen), but create a non-maximized window with the size of a maximized one.Beauty
This successfully maximizes the window in Ubuntu 14.04 too, keeping the top bar with the buttons we all know.Biggs
Works on Ubuntu 16.04 and linux mint. python2.7 testedParrotfish
@Fahlband Worked fine for me in a 3-monitor setup.Aubrey
this is what i'm looking for...worked perfect on windows 10Electrophoresis
C
49

This should work (at least with TkAgg):

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

(adopted from the above and Using Tkinter, is there a way to get the usable screen size without visibly zooming a window?)

Cagle answered 6/11, 2013 at 22:8 Comment(6)
Yay! This worked for me; it creates a maximized window that snaps to the edges of the screen and has the minimize, maximize/restore down and close buttons as it should.Beauty
However, you mean that this works with TkAgg, not TkApp, right?Beauty
Good catch (probably a typo)! TkAgg is a backend for Tk.Cagle
Just tested this for matplotlib 2 / python 3 . Works under windows!Silma
Alas, does not work on Debian linux, which doesn't have the 'zoomed' state.Mezoff
This is the solution that worked for me on Windows 11 with the default matplotlib installation.Hube
B
49

For me nothing of the above worked. I use the Tk backend on Ubuntu 14.04 which contains matplotlib 1.3.1.

The following code creates a fullscreen plot window which is not the same as maximizing but it serves my purpose nicely:

from matplotlib import pyplot as plt
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
Bumptious answered 20/5, 2014 at 8:59 Comment(6)
This was also the solution that worked for me (although it goes to full screen, not maximised window). Running on Redhat Enterprise Linux 6, python 2.7.10, matplotlib 1.4.3.Tarragon
Worked for me within Visual Studio 2015 on Windows 10 x64, python 3.5 except that I could not access the window border to close the figure, as it was above the top screen pixels.Escalator
For me, this doesn't create a maximized window either, but a fullscreen one. I didn't get any minimize, maximize/restore down and close buttons as normal windows have and I had to right-click on the window on the taskbar to be able to close it.Beauty
This goes full screen without showing the buttons that every window has. Tried on Ubuntu 14.04.Biggs
Working like a charm on Raspbian (jessie)Rabaul
It works fullscreen as others said, but on my multi-monitor setup goes onto a different monitor than is currently in use, which makes it non-functional for me.Mezoff
S
46

I usually use

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

before the call to plt.show(), and I get a maximized window. This works for the 'wx' backend only.

EDIT:

for Qt4Agg backend, see kwerenda's answer.

Succinctorium answered 26/9, 2012 at 9:53 Comment(8)
Using this, I get mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame' in Matplotlib 1.2.0Romish
It works with backend wx, I've updated the post accordingly. Likely the Tk backend you are using doesn't support this feature. Do you have the option to change matplotlib backend to 'wx'?Succinctorium
error on mac: mng.frame.Maximize(True) AttributeError: 'FigureManagerMac' object has no attribute 'frame'Heterosexuality
Is there a known solution to do this on the MacOSXbackend? The FigureManagerMac seems to have neither the attribute windownor frame.Haerr
I have the same issue on WindowsIllsuited
the OO interface: fig, ax = plt.subplots(1, 1) fig.canvas.manager.window.showMaximized() works in Qt5, couldn't get the 'WX' work on my machineBuseck
Similar error, like first comment. AttributeError: 'FigureManagerQT' object has no attribute 'frame'.Pearlinepearlman
Same issue on Ubuntu: mng.frame.Maximize(True) AttributeError: 'FigureManagerTk' object has no attribute 'frame'Seigniory
S
17

My best effort so far, supporting different backends:

from platform import system
def plt_maximize():
    # See discussion: https://mcmap.net/q/151237/-how-to-maximize-a-plt-show-window
    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)
Spouse answered 15/2, 2019 at 11:46 Comment(0)
H
11

I get mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame' as well.

Then I looked through the attributes mng has, and I found this:

mng.window.showMaximized()

That worked for me.

So for people who have the same trouble, you may try this.

By the way, my Matplotlib version is 1.3.1.

Handfast answered 17/12, 2013 at 0:6 Comment(4)
Thanks! This solution worked well for me. Running on Redhat Enterprise Linux 6, python 2.7.10, matplotlib 1.4.3.Tarragon
I know this will pop up a fullscreen window, but my plots will come up in a separate window when I type plt.show(). Not on this fullscreen window, any suggestion?Subcortex
It also works on python 3.6 on Debian and with Qt backend.Mountbatten
this does not run on windows 10 64bit with python 3.7Farmer
R
11

I found this for full screen mode on Ubuntu

#Show full screen
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
Ruttger answered 9/3, 2019 at 19:25 Comment(0)
E
10

This is kind of hacky and probably not portable, only use it if you're looking for quick and dirty. If I just set the figure much bigger than the screen, it takes exactly the whole screen.

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

In fact, in Ubuntu 16.04 with Qt4Agg, it maximizes the window (not full-screen) if it's bigger than the screen. (If you have two monitors, it just maximizes it on one of them).

Entomologize answered 2/12, 2016 at 10:37 Comment(0)
R
9

The one solution that worked on Win 10 flawlessly.

import matplotlib.pyplot as plt

plt.plot(x_data, y_data)

mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.show()
Rectilinear answered 23/11, 2018 at 15:21 Comment(0)
E
9
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()

Then call function maximize() before plt.show()

Eppes answered 31/3, 2020 at 12:57 Comment(0)
K
6

For backend GTK3Agg, use maximize() – notably with a lower case m:

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

Tested in Ubuntu 20.04 with Python 3.8.

Katlynkatmai answered 11/9, 2020 at 19:0 Comment(0)
I
4

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()
Iniquitous answered 26/9, 2019 at 0:44 Comment(0)
I
3

Pressing the f key (or ctrl+f in 1.2rc1) when focussed on a plot will fullscreen a plot window. Not quite maximising, but perhaps better.

Other than that, to actually maximize, you will need to use GUI Toolkit specific commands (if they exist for your specific backend).

HTH

Introrse answered 16/9, 2012 at 7:14 Comment(1)
This explains which key I kept accidentally hitting that fullscreened my windows! (And how to undo it.)Pilliwinks
F
2

Try using 'Figure.set_size_inches' method, with the extra keyword argument forward=True. According to the documentation, this should resize the figure window.

Whether that actually happens will depend on the operating system you are using.

Farika answered 16/9, 2012 at 15:43 Comment(0)
C
2

In my versions (Python 3.6, Eclipse, Windows 7), snippets given above didn't work, but with hints given by Eclipse/pydev (after typing: mng.), I found:

mng.full_screen_toggle()

It seems that using mng-commands is ok only for local development...

Calendar answered 18/4, 2018 at 6:35 Comment(0)
B
1

Ok so this is what worked for me. I did the whole showMaximize() option and it does resize your window in proportion to the size of the figure, but it does not expand and 'fit' the canvas. I solved this by:

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

plt.show()
Breen answered 5/11, 2016 at 10:42 Comment(0)
C
1

For Tk-based backend (TkAgg), these two options maximize & fullscreen the window:

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

When plotting into multiple windows, you need to write this for each window:

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

Here, both 'figures' are plotted in separate windows. Using a variable such as

figure_manager = plt.get_current_fig_manager()

might not maximize the second window, since the variable still refers to the first window.

Caelum answered 23/9, 2020 at 22:0 Comment(0)
V
1

I collected a few answers from the threads I was looking at when trying to achieve the same thing. This is the function I am using right now which maximizes all plots and doesn't really care about the backend being used. I run it at the end of the script. It does still run into the problem mentioned by others using multiscreen setups, in that fm.window.maxsize() will get the total screen size rather than just that of the current monitor. If you know the screensize you want them you can replace *fm.window.maxsize() with the tuple (width_inches, height_inches).

Functionally all this does is grab a list of figures, and resize them to matplotlibs current interpretation of the current maximum window size.

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())
Vicissitude answered 28/2, 2022 at 20:36 Comment(0)
T
1

I have tried most of above solutions but none of them works well on my Windows 10 with Python 3.10.5.

Below is what I found that works perfectly on my side.

import ctypes

mng = plt.get_current_fig_manager()
mng.resize(ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
Tillo answered 12/10, 2022 at 18:52 Comment(0)
R
0

Try plt.figure(figsize=(6*3.13,4*3.13)) to make the plot larger.

Reenareenforce answered 15/9, 2012 at 17:37 Comment(0)
I
0

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

Idonna answered 28/5, 2014 at 5:43 Comment(0)
C
0

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()
Countrydance answered 10/2, 2016 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.