Open In App

Save Plot To Numpy Array using Matplotlib

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Saving a plot to a NumPy array in Python is a technique that bridges data visualization with array manipulation allowing for the direct storage of graphical plots as array representations, facilitating further computational analyses or modifications within a Python environment. Let’s learn how to Save Plot to NumPy Array using Matplotlib.

How to Save Plot to NumPy Array

To save a plot to a NumPy array, one must first create the plot using a plotting library like Matplotlib, then, utilizing `canvas.tostring_rgb()` method to capture the plot as an RGB string and reshape this data into a NumPy array with appropriate dimensions.

Essential steps include:

  • Plotting and capturing the plot’s RGB representation
  • Reshaping it into an array, ensuring seamless integration of visualization into data analysis workflows.

Method 1: Using fig.canvas.tostring_rgb and numpy.fromstring

  • In this approach, the plot is created and drawn on the canvas. The canvas is drawn to render the plot and the rendered canvas is then converted to a raw RGB buffer using ‘buf= fig.canvas.tostring_rgb()‘.
  • The raw buffer is converted into a NumPy array representing the image. Finally, it prints the shape of the image array and a portion of pixel values along with their RGB values.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
fig.canvas.draw()
 
# Convert the canvas to a raw RGB buffer
buf = fig.canvas.tostring_rgb()
ncols, nrows = fig.canvas.get_width_height()
image = np.frombuffer(buf, dtype=np.uint8).reshape(nrows, ncols, 3)
 
print("Image shape:", image.shape)
print("First 3x3 pixels and RGB values:")
print(image[:3, :3, :])


Output:

Image shape: (480, 640, 3)
First 3x3 pixels and RGB values:
[[[255 255 255]
  [255 255 255]
  [255 255 255]]

 [[255 255 255]
  [255 255 255]
  [255 255 255]]

 [[255 255 255]
  [255 255 255]
  [255 255 255]]]
  • The dimensions of the image are (480, 640, 3), which indicates:
  • 480: This is the height of the image in pixels.
  • 640: This is the width of the image in pixels.
  • 3: This represents the number of color channels in the image. Since the value is 3, it’s likely an RGB image where each pixel has three values representing red, green, and blue intensities.

Method 2: Saving the plot to a io.BytesIO object

  • This method involves creating a plot with Matplotlib and saving it to a BytesIO object in memory (as PNG) a temporary buffer in memory, instead of directly to a file.
  • The BytesIO object is then read into a PIL Image, using the Pillow (PIL Fork) library which is converted to a NumPy array. This approach is efficient for converting plots to arrays without needing to save and read from disk.

Python3




import matplotlib.pyplot as plt
import numpy as np
import io
from PIL import Image
 
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
 
# Create a bytes buffer to save the plot
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
 
# Open the PNG image from the buffer and convert it to a NumPy array
image = np.array(Image.open(buf))
# Close the buffer
buf.close()
 
print("Image shape:", image.shape)
print("First 3x3 pixels and RGB values:")
print(image[:3, :3, :])


Output:

Image shape: (480, 640, 4)
First 3x3 pixels and RGB values:
[[[255 255 255 255]
  [255 255 255 255]
  [255 255 255 255]]

 [[255 255 255 255]
  [255 255 255 255]
  [255 255 255 255]]

 [[255 255 255 255]
  [255 255 255 255]
  [255 255 255 255]]]

The output (480, 640, 4) gives a NumPy array representing an image with a height of 480 pixels, a width of 640 pixels, and four color channels (RGBA). While the alpha channel might not be explicitly used in the plot data itself, its presence could be due to Matplotlib’s handling of PNG transparency or the behavior of the image processing library used.

  • Matplotlib with PNG transparency: When saving a Matplotlib plot to PNG format using plt.savefig with transparency enabled, the resulting image might have an alpha channel even if the plot itself doesn’t explicitly use transparency. This behavior depends on Matplotlib’s internal handling of PNG images.
  • External library (PIL): While using an external library like PIL to open the image, it might add an alpha channel even if the original PNG from Matplotlib didn’t have it. Some image processing libraries like PIL might assume or add an alpha channel by default for consistency.

Conclusion

In conclusion, converting plots to NumPy arrays in Python enhances data visualization by integrating it with array-based computation, offering flexibility across various applications.



Similar Reads

NumPy save() Method | Save Array to a File
The NumPy save() method is used to store the input array in a binary file with the 'npy extension' (.npy). Example: C/C++ Code import numpy as np a = np.arange(5) np.save('array_file', a) SyntaxSyntax: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Parameters: file: File or filename to which the data is saved. If the file is a string or
2 min read
How to Save a Plot to a File Using Matplotlib?
Matplotlib is a widely used Python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. In this article, we will see how to save a Matplotlib plot as an image file. Save a plot in MatplotlibBelow are the ways by which we can save a plot to a file using Matplotlib in Python: Us
3 min read
Normal Distribution Plot using Numpy and Matplotlib
In this article, we will see how we can create a normal distribution plot in python with numpy and matplotlib module. What is Normal Distribution? Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics becaus
3 min read
How to Save Seaborn Plot to a File in Python?
Seaborn provides a way to store the final output in different desired file formats like .png, .pdf, .tiff, .eps, etc. Let us see how to save the output graph to a specific file format. Saving a Seaborn Plot to a File in Python Import the inbuilt penguins dataset from seaborn package using the inbuilt function load_dataset. C/C++ Code # Import the s
2 min read
Save multiple matplotlib figures in single PDF file using Python
In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
3 min read
Save Matplotlib Figure as SVG and PDF using Python
In this article, we will see how can we save the Matplotlib figure as Scalable Vector Graphics(SVG) using Python or any other file format for further use. The required modules for this tutorial are Matplotlib. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. If you had not installed the
3 min read
How to save a NumPy array to a text file?
Let us see how to save a numpy array to a text file. Method 1: Using File handling Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function. Below are some programs of the this approach: Example 1: C
3 min read
How to save Matplotlib Animation?
In this article, we will learn How to save Matplotlib Animation. The animated graphs made with the help of matplotlib can be saved as videos in Python. As we can create captivating animations using the matplotlib library. If you want to learn to create animations, here is a link to the article to create animations using the matplotlib. In this arti
2 min read
How To Save Multiple Numpy Arrays
NumPy is a powerful Python framework for numerical computing that supports massive, multi-dimensional arrays and matrices and offers a number of mathematical functions for modifying the arrays. It is an essential store for Python activities involving scientific computing, data analysis, and machine learning. What is a Numpy array?A NumPy array is a
3 min read
PyQtGraph - Getting Plot Item from Plot Window
In this article we will see how we can get the plot item of plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and s
2 min read
Practice Tags :