In Python and Matplotlib, it is easy to either display the plot as a popup window or save the plot as a PNG file. How can I instead save the plot to a numpy array in RGB format?
Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.
For plotting graphs in Python, we will use the Matplotlib library. Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot(), which is used to plot two-dimensional data.
Click the chart that you want to save as a picture. Choose Copy from the ribbon, or press CTRL+C on your keyboard . Switch to the application you want to copy the chart to. If you're saving as a separate image file open your favorite graphics editor, such as Microsoft Paint.
This is a handy trick for unit tests and the like, when you need to do a pixel-to-pixel comparison with a saved plot.
One way is to use fig.canvas.tostring_rgb
and then numpy.fromstring
with the approriate dtype. There are other ways as well, but this is the one I tend to use.
E.g.
import matplotlib.pyplot as plt import numpy as np # Make a random plot... fig = plt.figure() fig.add_subplot(111) # If we haven't already shown or saved the plot, then we need to # draw the figure first... fig.canvas.draw() # Now we can save it to a numpy array. data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With