Save Plot To Numpy Array using Matplotlib
Last Updated :
06 Mar, 2024
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
How to Save a Plot to a File Using Matplotlib? Matplotlib is a popular Python library to create plots, charts, and graphs of different types. show() is used to plot a plot, but it doesn't save the plot to a file. In this article, we will see various methods through which a Matplotlib plot can be saved as an image file.Methods to Save a Plot in M
2 min read
Plotting Numpy Array Using Seaborn Seaborn, a powerful Python data visualization library built on top of matplotlib, provides a range of tools for creating informative and attractive statistical graphics. One of its key features is the ability to plot numpy arrays, which are fundamental data structures in Python. This article delves
4 min read
Multiplots in Python using Matplotlib Matplotlib is a Python library that can be used for plotting graphs and figures. Plotting multiplots or multiple plots are often required either for comparing the two curves or show some gradual changes in the multiple plots, and this can be done using Subplots. Subplots are one of the most importan
3 min read
Matplotlib.pyplot.sci() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
2 min read
Matplotlib.pyplot.savefig() in Python savefig() function in Python is used to save a plot created with Matplotlib to a file. It supports various formats like PNG, PDF, SVG, and more. This method allows you to specify additional parameters like file name, resolution, layout, and transparency, giving you control over the appearance and qu
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 visua
3 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
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 probabilit
2 min read
How to plot a complex number in Python using Matplotlib ? In this article we will learn how to plot complex number in Python using Matplotlib. Let's discuss some concepts : Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designe
3 min read
How to plot data from a text file using Matplotlib? Perquisites: Matplotlib, NumPy In this article, we will see how to load data files for Matplotlib. Matplotlib is a 2D Python library used for Date Visualization. We can plot different types of graphs using the same data like: Bar GraphLine GraphScatter GraphHistogram Graph and many. In this article,
3 min read