Saving what I see in PyPlot

Asked by At

It seems I cannot understand what I am supposed to do in Python MatplotLib in order to save more or less exactly what I see on my screen.

This is the test code I prepared:

import matplotlib.pyplot as plt
import numpy as np

def main():
    values = [712, 806, 858, 990, 1158, 1126, 166]
    xlabels = np.arange(2013, 2020)
    ylabels = ylabels = np.arange(400,1300,400)
    index = np.arange(len(xlabels))

    fig = plt.figure(1, figsize=(12,16), dpi=100)
    plt.bar(index, values, color='grey')
    plt.xticks(index, xlabels, fontsize=30)
    plt.yticks(ylabels, ylabels, fontsize=30)
    plt.ylim((0, 1400))
    plt.title('Title', fontsize=40)

    plt.savefig('../figs/test.png')
    plt.show()

# -----------------------------------------
if __name__ == "__main__":
    main()

This is what I see on the screen, that I saved using the GUI: Shown on screen, and saved using the Python GUI

This is the image saved by savefig:

Saved by savefig

If I use fig.savefig(...) in place of plt.savefig(...) nothing changes.

What am I doing wrong?

2 Answers

0
Community On Best Solutions

Have you tried to resize like this :

If you've already got the figure created you can quickly do this:

fig.set_size_inches(12,16)
fig.savefig('../figs/test.png', dpi=100)

To propagate the size change to an existing gui window add forward=True

fig.set_size_inches(12,16, forward=True)

from this topic : How do you change the size of figures drawn with matplotlib?

1
ImportanceOfBeingErnest On

Say you have a monitor resolution of 1080 pixels in vertical direction. Maybe you have a taskbar present and also the matplotlib figure window has a title and navigation bar. So in total you may have some 950 pixel available to show your figure. This means the figure height in inches should be no larger than 950 / dpi. In your case

fig = plt.figure(figsize=(12, 950./100), dpi=100)

Inversely, if you really want to show and save a 16 inch figure with 100 dpi, you would need to add a scrollbar to your figure window, similar to Scrollbar on Matplotlib showing page.