2

I try to save the plot to a numpy array in RGB format and find a sample code from Matplotlib: save plot to numpy array.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()


fig.tight_layout(pad=0)
fig.canvas.draw()

data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
print(data.shape)
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

However the length of bytes generated from fig.canvas.tostring_rgb()is 3686400 and the shape of fig.canvas.get_width_height() is (640,480,3), which is mismatched, since 640 * 480 *3 = 921600.

It happens only when I run this code on windows using terminal. Jupyer notebook on Windows and Linux output correct bytes which has length 921600.

matplotlib version is 3.4.2.

gboffi
  • 22,939
  • 8
  • 54
  • 85
xinwei li
  • 31
  • 2
  • The LENGTH IN BYTES of the `data` array would be indeed 3686400, if Numpy uses `int32` to store `uint8`. Question: is 3686400 the SHAPE of `data` or is it the length in bytes? – gboffi May 25 '21 at 18:17
  • Actually this is what makes me confused. `print(data.shape)` ouput 3686400 on windows terminal, but output 921600 on juputer notebook. – xinwei li Oct 11 '21 at 07:25

1 Answers1

1

I got the same problem, and it was solved by adding the following code at the beginning of the script,

import matplotlib
matplotlib.use("Agg")

Bing
  • 91
  • 1
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 20 '22 at 10:40