How to maximize a plt.show() window

Question:

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()
Asked By: Santiago Lovera

||

Answers:

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

Answered By: Navin

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

Answered By: pelson

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.

Answered By: Roland Smith

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.

Answered By: gg349

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())
Answered By: Dan Christensen

With Qt backend (FigureManagerQT) proper command is:

figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
Answered By: kwerenda

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

Answered By: dinvlad

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.

Answered By: Alan Wang

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.

Answered By: Pythonio

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()
Answered By: peschü

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

Answered By: Blairg23

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()
Answered By: MikeTeX

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()
Answered By: ArmandduPlessis

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

Answered By: Mark

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…

Answered By: Antti A

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()
Answered By: Zeds Zen

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)
Answered By: Martin R.

I found this for full screen mode on Ubuntu

#Show full screen
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
Answered By: Westly White

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()
Answered By: ch271828n
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()

Answered By: Adhun Thalekkara

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.

Answered By: shredEngineer

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.

Answered By: CRTejaswi

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())
Answered By: UCDS

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))
Answered By: n a
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.