How to save a chart to a PNG image?

Asked

Viewed 937 times

3

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

How do I display my data:

import matplotlib.pyplot as plt

data = (
    (1,1),
    (2,2),
    (3,4),
    (4,7)
    # mais umas 300 linhas de dados do experimento...
)

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

plt.plot(x,y)
plt.show()

How do I save the image?

2 answers

4


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:

plt.savefig('resultado.png')

The parameters of the method are:

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

  • dpi, the resolution in points 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.

Example:

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')

plt.savefig('graph.png')

Produced:

inserir a descrição da imagem aqui

1

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

pylab.savefig('foo.png')

Of itself pyplot

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.