Search code examples
pythonmatplotlibplotwindowfigure

When using matplotlib, how can I make each figure always plot in the same location on the screen?


I have a Python script that plots 3 figures using matplotlib. When I run this script, and then close the 3 figures and rerun it, the figures appear in different locations on my screen in the second run compared to the first run.

(For example, in the first run, the first figure might be positioned near the upper left corner of the screen, with the second and third figures staggered or cascaded toward the lower right relative to the first figure. In the second run, the first figure might be positioned closer to the middle of the screen, the second figure might be cascaded relative to the first, while the third figure may be positioned near the upper left corner of the screen.)

Is there a way to prevent this inconsistency of figure placement from occurring across different runs? In other words, is there a way to force Python to maintain the same placement of the figures on the screen across each run?


Solution

  • While I still hope for a more elegant answer (such as a way to turn off the apparent randomization of figure placement), it appears that the figure manager can be used to fix the on-screen placement of the 3 figures across runs — at least on Window 10. Here is a near-minimal reproducible example:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    mpl.use("TkAgg")  # ensures that the backend is set to TkAgg
    
    plt.figure(num=1, figsize=(6,5))
    mngr = plt.get_current_fig_manager()
    mngr.canvas.manager.window.wm_geometry("+%d+%d" % (50, 100))
    
    plt.figure(num=2, figsize=(6,5))
    mngr = plt.get_current_fig_manager()
    mngr.canvas.manager.window.wm_geometry("+%d+%d" % (70, 120))
    
    plt.figure(num=3, figsize=(6,5))
    mngr = plt.get_current_fig_manager()
    mngr.canvas.manager.window.wm_geometry("+%d+%d" % (90, 140))
    
    plt.show()
    

    This is adapted from several answers to this question.