How to maximize a plt.show() window using Python

PythonMatplotlib

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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. Cheers

Solution 2 - Python

With Qt backend (FigureManagerQT) proper command is:

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

This should work (at least with TkAgg):

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

(adopted from the above and https://stackoverflow.com/questions/13129985/using-tkinter-is-there-a-way-to-get-the-usable-screen-size-without-visibly-zoom)

Solution 6 - Python

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.

Solution 7 - Python

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

Solution 8 - Python

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.

Solution 9 - Python

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

Solution 10 - Python

I found this for full screen mode on Ubuntu

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

Solution 11 - Python

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

Solution 12 - Python

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

Solution 13 - Python

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

Solution 14 - Python

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

Solution 15 - Python

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.

Solution 16 - Python

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.

Solution 17 - Python

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...

Solution 18 - Python

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

Solution 19 - Python

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

Solution 20 - Python

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.

Solution 21 - Python

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

Solution 22 - Python

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

Solution 23 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSantiago LoveraView Question on Stackoverflow
Solution 1 - PythonPythonioView Answer on Stackoverflow
Solution 2 - PythonkwerendaView Answer on Stackoverflow
Solution 3 - PythonDan ChristensenView Answer on Stackoverflow
Solution 4 - PythonpeschüView Answer on Stackoverflow
Solution 5 - PythondinvladView Answer on Stackoverflow
Solution 6 - Pythongg349View Answer on Stackoverflow
Solution 7 - PythonMartin R.View Answer on Stackoverflow
Solution 8 - PythonAlan WangView Answer on Stackoverflow
Solution 9 - PythonMarkView Answer on Stackoverflow
Solution 10 - PythonWestly WhiteView Answer on Stackoverflow
Solution 11 - PythonZeds ZenView Answer on Stackoverflow
Solution 12 - PythonAdhun ThalekkaraView Answer on Stackoverflow
Solution 13 - PythonpelsonView Answer on Stackoverflow
Solution 14 - Pythonch271828nView Answer on Stackoverflow
Solution 15 - PythonshredEngineerView Answer on Stackoverflow
Solution 16 - PythonRoland SmithView Answer on Stackoverflow
Solution 17 - PythonAntti AView Answer on Stackoverflow
Solution 18 - PythonNavinView Answer on Stackoverflow
Solution 19 - PythonArmandduPlessisView Answer on Stackoverflow
Solution 20 - PythonCRTejaswiView Answer on Stackoverflow
Solution 21 - PythonBlairg23View Answer on Stackoverflow
Solution 22 - PythonMikeTeXView Answer on Stackoverflow
Solution 23 - PythonUCDSView Answer on Stackoverflow