def add_figure(self, figure: plt.Figure, caption: Optional[str] = None): buf = io.BytesIO() figure.set_size_inches(6, 4) figure.set_dpi(300) figure.savefig(buf, format="png") b64url = "data:image/png;base64,%s" % base64.b64encode( buf.getvalue()).decode("utf8") self.__elements.append({"kind": "figure", "url": b64url}) plt.clf()
def _mpl_figure_to_rgb_img(fig: plt.Figure, height, width): fig.set_dpi(100) fig.set_size_inches(width / 100, height / 100) canvas = fig.canvas canvas.draw() width, height = np.round(fig.get_size_inches() * fig.get_dpi()).astype(int) # image = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8') img = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3) plt.close(fig) return img