Open In App

Save Plot To Numpy Array using Matplotlib

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:

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




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]]]

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




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.

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.


Article Tags :