import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas import numpy as np # Generate some data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a figure and plot the data fig, ax = plt.subplots() ax.plot(x, y) # Create a canvas for the figure canvas = FigureCanvas(fig) # Render the figure to a png file canvas.print_png('figure.png')
import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas import numpy as np # Generate some data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a figure and plot the data fig, ax = plt.subplots() ax.plot(x, y) # Create a canvas for the figure canvas = FigureCanvas(fig) # Render the figure to a numpy array canvas.draw() width, height = fig.get_size_inches() * fig.get_dpi() image = np.frombuffer(canvas.buffer_rgba(), dtype='uint8') image = image.reshape(int(height), int(width), 4) # Display the image plt.imshow(image) plt.show()This code generates a sine wave plot, renders it to a numpy array using the print_rgba() method of FigureCanvasAgg, and displays the resulting image.