How to make pylab.savefig() save image for 'maximized' window instead of default size

前端 未结 8 2113
一整个雨季
一整个雨季 2020-12-12 17:49

I am using pylab in matplotlib to create a plot and save the plot to an image file. However, when I save the image using pylab.savefig( image_name ), I find tha

相关标签:
8条回答
  • 2020-12-12 18:51

    You can look in a saved figure it's size, like 1920x983 px (size when i saved a maximized window), then I set the dpi as 100 and the size as 19.20x9.83 and it worked fine. Saved exactly equal to the maximized figure.

    import numpy as np
    import matplotlib.pyplot as plt
    x, y = np.genfromtxt('fname.dat', usecols=(0,1), unpack=True)
    a = plt.figure(figsize=(19.20,9.83))
    a = plt.plot(x, y, '-')
    plt.savefig('file.png',format='png',dpi=100)
    
    0 讨论(0)
  • 2020-12-12 18:53

    I did the same search time ago, it seems that he exact solution depends on the backend.

    I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.

    Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.

    def maximize(backend=None,fullscreen=False):
        """Maximize window independently on backend.
        Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
        if backend is None:
            backend=matplotlib.get_backend()
        mng = plt.get_current_fig_manager()
    
        if fullscreen:
            mng.full_screen_toggle()
        else:
            if backend == 'wxAgg':
                mng.frame.Maximize(True)
            elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
                mng.window.showMaximized()
            elif backend == 'TkAgg':
                mng.window.state('zoomed') #works fine on Windows!
            else:
                print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
        plt.show()
    
        plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)
    
    0 讨论(0)
提交回复
热议问题