Search code examples
pythonmatplotlib

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


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 that the SIZE image saved is the same as the image that is shown when I use pylab.show().

As it happens, I have a lot of data in the plot and when I am using pylab.show(), I have to maximize the window before I can see all of the plot correctly, and the xlabel tickers don't superimpose on each other.

Is there anyway that I can programmatically 'maximize' the window before saving the image to file? - at the moment, I am only getting the 'default' window size image, which results in the x axis labels being superimposed on one another.


Solution

  • You set the size on initialization:

    fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!
    

    Edit:

    If the problem is with x-axis ticks - You can set them "manually":

    fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here
    

    And so on with other aspects of Your plot. You can configure it all. Here's an example:

    from numpy import arange
    import matplotlib
    # import matplotlib as mpl
    import matplotlib.pyplot
    # import matplotlib.pyplot as plt
    
    x1 = [1,2,3]
    y1 = [4,5,6]
    x2 = [1,2,3]
    y2 = [5,5,5]
    
    # initialization
    fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # The size of the figure is specified as (width, height) in inches
    
    # lines:
    l1 = fig2.add_subplot(111).plot(x1,y1, label=r"Text $formula$", "r-", lw=2)
    l2 = fig2.add_subplot(111).plot(x2,y2, label=r"$legend2$" ,"g--", lw=3)
    fig2.add_subplot(111).legend((l1,l2), loc=0)
    
    # axes:
    fig2.add_subplot(111).grid(True)
    fig2.add_subplot(111).set_xticks(arange(1,3,0.5))
    fig2.add_subplot(111).axis(xmin=3, xmax=6) # there're also ymin, ymax
    fig2.add_subplot(111).axis([0,4,3,6]) # all!
    fig2.add_subplot(111).set_xlim([0,4])
    fig2.add_subplot(111).set_ylim([3,6])
    
    # labels:
    fig2.add_subplot(111).set_xlabel(r"x $2^2$", fontsize=15, color = "r")
    fig2.add_subplot(111).set_ylabel(r"y $2^2$")
    fig2.add_subplot(111).set_title(r"title $6^4$")
    fig2.add_subplot(111).text(2, 5.5, r"an equation: $E=mc^2$", fontsize=15, color = "y")
    fig2.add_subplot(111).text(3, 2, unicode('f\374r', 'latin-1'))
    
    # saving:
    fig2.savefig("fig2.png")
    

    So - what exactly do You want to be configured?