Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: save plot to numpy array

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?

like image 426
user1003146 Avatar asked Oct 19 '11 12:10

user1003146


People also ask

Can you save a matplotlib plot?

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.

Can you plot Numpy array?

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.

How do you turn a plot into a picture?

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.


1 Answers

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,)) 
like image 99
Joe Kington Avatar answered Sep 23 '22 08:09

Joe Kington