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 = (
(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?
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:
plt.savefig('resultado.png')
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.
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: