How to save a graphic in a PNG image?

Posted on

Question :

I have some data from an experiment, and would like to save them as PNG. To display the data, I simply do show() . However, I would like to save directly as PNG to not get print out of the screen.

How do I display my data:

import matplotlib.pyplot as plt

data = (
    # mais umas 300 linhas de dados do experimento...

x = [d[0] for d in data]
y = [d[1] for d in data]


How do I save the image?


Answer :

The same object pyplot referenced by plt has the method savefig . :

savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

So, if you need to save the chart, just do:


The method parameters are:

  • fname , a string that indicates the path where the image or object in a file already opened by Python will be saved;

  • dpi , the resolution in dots per inch;

  • quality , image quality between 1 and 100; the bigger the better, only used when the format is JPG or JPEG;

Other parameters are much less used and can be seen directly in the documentation.


import matplotlib.pyplot as plt
import random

x = range(20)
y = [random.randint(0, 10) for _ in range(20)]

fig, ax = plt.subplots()
ax.plot(x, y, 'o')




You can use the savefig method, as in the example:


Of the pyplot itself



Leave a Reply

Your email address will not be published. Required fields are marked *