Convert Matplotlib Figure to NumPy array

Matplotlib is a widely used plotting library in Python that allows users to create various types of visualizations. One common task you might across when working with Matplotlib is to convert a plotted figure into a NumPy array. This conversion can be useful in scenarios where you want to manipulate or analyze your matplotlib graphs further using NumPy or other scientific computing libraries.

In this article, we will explore different methods to convert a Matplotlib figure to a NumPy array, providing you with the necessary knowledge to accomplish this task in your own projects.


Method 1: Using canvas and tostring_rgb()

The first method involves using the canvas and tostring_rgb() functions from the Matplotlib library. The canvas function provides a representation of the figure as an image, and tostring_rgb() converts it to a string in RGB format.

Let’s see how this can be done step by step:

Step 1: Create a sample figure

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [2, 4, 1, 5, 2])

In this code snippet, we create a sample figure using Matplotlib. The subplots() function creates a new figure and returns a tuple containing the figure object fig and an Axes object ax.


Step 2: Create and Render Canvas

canvas = fig.canvas
canvas.draw()

In this step, we obtain the figure’s canvas using fig.canvas. The canvas is the drawing area of the figure. We then call the draw() method to render the figure on the canvas.


Step 3: Retrieve width and height, and convert to NumPy array

width, height = canvas.get_width_height()
image_array = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
image_array = image_array.reshape(height, width, 3)

In this step, we retrieve the width and height of the canvas using get_width_height(). These dimensions are required to reshape the NumPy array correctly.

We then use tostring_rgb() to convert the canvas to a string in RGB format, and finally, use np.frombuffer() to convert the string to a NumPy array with the specified data type. The array is then reshaped to match the width, height, and RGB channels.


Step 4: Display the NumPy array

print(image_array)

Finally, we display the NumPy array to verify the conversion. You can perform further operations on this array using NumPy or any other scientific computing library.


Method 2: Using FigureCanvasAgg and to_array()

The second method involves using the FigureCanvasAgg and tarry() functions provided by the Matplotlib library. This approach provides similar functionality to the first method but with a different set of functions.

Let’s walk through the steps of this method:

Step 1: Create a sample figure

from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
canvas = FigureCanvasAgg(fig)

As before, we create a sample figure using Matplotlib. This time, we also create a canvas from a “FigureCanvasAgg” object. We will be using this object later to obtain the numpy array.


Step 2: Convert figure to NumPy array

ax.plot([1, 2, 3, 4, 5], [2, 4, 1, 5, 2])
canvas.draw()

Here we draw our graph using the plot() function of the axis object. We then call the draw() method to render the figure on the canvas. Every time a change is made to the figure (graphs), then canvas draw() method needs to be called.


Step 3: Convert canvas to NumPy array

image_array = np.array(canvas.buffer_rgba())

We now call the buffer_rgba() function on our canvas object to obtain a NumPy array representation of the matplotlib figure


Step 4: Display the NumPy array

print(image_array)

Finally, we display the NumPy array to verify the conversion.


This marks the end of the Convert Matplotlib Figure to NumPy array Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments