Render a Matplotlib figure as a component.
(fig: plt.Figure | None = None, label: str = "plot", component_id: str | None = None, **kwargs)
| 394 | |
| 395 | @with_render_tracking("matplotlib") |
| 396 | def matplotlib(fig: plt.Figure | None = None, label: str = "plot", component_id: str | None = None, **kwargs) -> ComponentReturn: |
| 397 | """Render a Matplotlib figure as a component.""" |
| 398 | |
| 399 | if fig is None: |
| 400 | fig, ax = plt.subplots() |
| 401 | ax.plot([0, 1, 2], [0, 1, 4]) |
| 402 | |
| 403 | # Save the figure as a base64-encoded PNG |
| 404 | buf = io.BytesIO() |
| 405 | fig.savefig(buf, format="png") |
| 406 | buf.seek(0) |
| 407 | img_b64 = base64.b64encode(buf.read()).decode() |
| 408 | |
| 409 | component = { |
| 410 | "type": "matplotlib", |
| 411 | "id": component_id, |
| 412 | "label": label, |
| 413 | "image": img_b64, # Store the image data |
| 414 | } |
| 415 | |
| 416 | return ComponentReturn( |
| 417 | component_id, component |
| 418 | ) # Returning ID for potential tracking |
| 419 | |
| 420 | |
| 421 | @with_render_tracking("playground") |
no test coverage detected