gradio · difficulty ◆◆
gradio Plot — hand it a figure, not a picture
Return the figure object: matplotlib becomes a small bitmap, plotly becomes live SVG, and both are one component.
gr.Plot never receives an image — it receives a figure object and decides from the object's module name whether to ship 7,031 characters of webp or a JSON chart the browser draws itself.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ gr.Plot()- Gradio 3.0
- Introduced
- 5 → 16 params
- Signature
- 1
- Events
- 7,031 vs 20,850 chars
- Same 5x3 line chart
2022-05-16, PR #805 — shipped alongside Blocks
3.0 to 6.30.0: 11 in 4.0, 14 in 5.0, 15 in 6.0, +buttons in 6.30.0
change — and it also fires when you set the plot from a handler
base64 payload as webp vs png, measured in 6.30.0 (jpg 15,462, svg 26,994)
What it does
gr.Plot is the output component for charts. You return the figure itself — a matplotlib Figure, a plotly Figure, an altair Chart, a bokeh model — and gradio encodes it for you: matplotlib gets saved to a data: URL (webp by default), everything else is serialised to JSON and drawn client-side by plotly.js, vega or bokeh. It is not gr.Image: paths, numpy arrays and PIL images are rejected, because the whole point is that you never call savefig. There are 16 parameters in 6.30.0 and exactly one event, change.
Why it matters
The moment your function returns numbers, a chart is the demo. gr.Plot is the shortest path from 'my model logs a loss curve' to 'a visitor sees it' — no cache directory, no image component, no figsize bookkeeping in a second place. And the two code paths are a real UX decision you make by returning a different object: matplotlib gives a static, tiny, themable-by-you bitmap; plotly gives hover tooltips, box zoom and a PNG export button, paid for in JSON and client CPU.
Example
$ import gradio as gr
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def forecast(months):
x = np.arange(1, months + 1)
y = 120 + 18 * x + 12 * np.sin(x)
fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(x, y, marker="o")
ax.set_title("signup forecast")
ax.set_xlabel("month")
return fig
with gr.Blocks(title="forecast") as demo:
months = gr.Slider(3, 24, value=12, step=1, label="months")
run = gr.Button("Forecast")
chart = gr.Plot(label="signups")
run.click(forecast, months, chart)
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
The Blocks page renders top to bottom: a Slider labeled "months" (3 to 24, sitting at 12), a Button reading "Forecast", then the Plot labeled "signups" showing an empty placeholder box. One click posts to /gradio_api/queue/join and the placeholder is replaced by a single <img> whose src is data:image/webp;base64,UklGR… — naturalWidth 500, naturalHeight 300, and the CSS box is exactly 500x300 as well. Nothing is uploaded and no file lands on disk: the figure is encoded in memory and inlined in the response.Verified in gradio 6.30.0 + matplotlib 3.11.2: real launch on 7860, then headless Chromium clicked the button and read naturalWidth / getBoundingClientRect back. 500x300 is figsize=(5, 3) times matplotlib's default dpi of 100 — gr.Plot does not scale the bitmap to the column width, which is 626 px in this layout.
$ import numpy as np
import plotly.express as px
import gradio as gr
rng = np.random.default_rng(0)
def embedding(n):
x = rng.normal(size=n)
y = x * 0.7 + rng.normal(size=n)
return px.scatter(x=x, y=y, color=y, title=f"{n} samples",
labels={"x": "dim 1", "y": "dim 2"})
with gr.Blocks() as demo:
n = gr.Slider(50, 500, value=200, step=50, label="samples")
p = gr.Plot(label="embedding")
n.change(embedding, n, p)
demo.launch()* Running on local URL: http://127.0.0.1:7863
* To create a public link, set `share=True` in `launch()`.
Same component, completely different DOM: after the Slider moves to 350, the output is a div.js-plotly-plot holding an SVG scene with 350 .point elements and a .modebar of nine controls — "Download plot as a PNG", Zoom, Pan, Box Select, Lasso Select, Zoom in, Zoom out, Autoscale, Reset axes — plus the footer "Produced with Plotly.js (v3.3.1)". No <img> and no base64 anywhere: the figure crossed the wire as JSON (7,040 characters for a three-bar chart) and plotly.js drew it.Verified in gradio 6.30.0 + plotly 7.1.0: slider clicked at 70% of its track (value became 350), then document.querySelectorAll('.point').length and the modebar data-title list read from the live page. Hover tooltips, drag-zoom and the PNG download all work because the chart is real DOM, not pixels.
$ import random
import gradio as gr
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def sample():
series = [random.randint(80, 140) for _ in range(20)]
fig, ax = plt.subplots(figsize=(5, 2.5))
ax.plot(series)
ax.set_ylim(60, 160)
return fig
with gr.Blocks() as demo:
p = gr.Plot(label="requests / 2s")
timer = gr.Timer(2)
timer.tick(sample, None, p)
demo.launch()* Running on local URL: http://127.0.0.1:7862
* To create a public link, set `share=True` in `launch()`.
A chart that redraws itself: with one browser tab open on the page, the handler ran 10 times in 22 seconds at every=2 — the img inside the plot swapped to a new data:image/webp;base64 payload each time (500x250 px, matching figsize=(5, 2.5)). No button, no click, no polling from you: gr.Timer queues the job and the component repaints.Verified in gradio 6.30.0 by counting server-side handler prints while headless Chromium held the page open (10 ticks in ~22 s, first tick ~2 s after load). Replace gr.Timer with gr.Plot(every=2) only if you also give the plot a job to run — a bare every= on an output with no listener fires nothing (0 calls in my test).
$ import base64
import gradio as gr
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def chart():
fig, ax = plt.subplots(figsize=(4, 3))
ax.bar(["a", "b", "c"], [3, 7, 2])
return fig
def export(plot_value):
raw = base64.b64decode(plot_value.plot.split(",", 1)[1])
return f"{plot_value.type} · {len(raw)} bytes · {raw[8:12].decode()}"
with gr.Blocks() as demo:
p = gr.Plot(value=chart, label="bars")
b = gr.Button("Export current chart")
out = gr.Textbox(label="saved")
b.click(export, p, out)
demo.launch()* Running on local URL: http://127.0.0.1:7861
* To create a public link, set `share=True` in `launch()`.
A Plot really can be an input. Clicking the button hands the handler a PlotData object — type='matplotlib', plot='data:image/webp;base64,UklGRn4NAABXRUJQVlA4IHI…' — and base64-decoding the part after the comma yields 1,940 bytes starting with the WEBP magic. The Textbox came back reading exactly "matplotlib · 1940 bytes · WEBP".Verified in gradio 6.30.0: value= took a zero-argument callable, the browser ran the click, and the server printed PlotData(type='matplotlib', plot='data:image/webp;base64,…'). The same trick over the Python client needs a dict, not the bare data URL — see the warning callout.
Common flags
- value
- A figure object, or a zero-argument callable that gradio calls on each page load. Strings, paths and numpy arrays raise AttributeError: 'str' object has no attribute '__module__'.
- format
- 'webp' by default (since 4.22.0). Same 5x3 line chart, measured base64 length: webp 7,031 · jpg 15,462 · png 20,850 · svg 26,994. Applies to matplotlib only — plotly is JSON either way.
- every
- Timer or float. It only re-runs a job that exists (a value callable or a listener); and pointing .change() at the plot you also write to turns every= into an infinite render loop.
- label / show_label
- label renders above the chart. It does not reach the image: every plot <img> carries alt="undefined plot visualising provided data" in 6.30.0.
- scale / min_width
- Row layout knobs for the wrapper. The matplotlib bitmap itself stays at figsize x dpi pixels, so a wide column gives you whitespace, not a bigger chart.
- buttons
- A list of gr.Button rendered in the plot's own corner toolbar (6.30.0). I attached gr.Button("Export CSV") and its .click() listener fired normally.
- elem_id / elem_classes
- CSS hooks on the component wrapper — the only way to give the empty state or the image a border of your own.
History
Born with Blocks in 3.0
gr.Plot arrived in Gradio 3.0 (2022-05-16, PR #805 by @dawoodkhan82) — the same release that introduced Blocks. It was five parameters (value, label, show_label, visible, elem_id) in the monolithic gradio/components.py, declared as class Plot(Changeable, Clearable, IOComponent), so a chart came with a clear button. Its docstring then read: 'Preprocessing: this component does *not* accept input.' Bokeh had to arrive as a pre-built json_item dict, and altair was not supported at all.
Six years, four libraries, one event
Altair values landed in 3.13.0. The 4.0 rewrite moved the class into gradio/components/plot.py and took it from 5 to 11 parameters; the format parameter arrived in 4.22.0 (PR #7680), the change/load events were fixed in 5.16.0 (PR #10544), 6.0 brought it to 15, and 6.18.0 (11 Jun 2026, PR #13522) finally started closing matplotlib figures after rendering them. 6.20.0 fixed autosize plotly charts collapsing to zero height, and 6.30.0 added buttons — 16 parameters, still exactly one event.
Under the hood
What postprocess actually does with your figure
The type decision is a string check, not isinstance: `if isinstance(value, ModuleType) or "matplotlib" in value.__module__` picks the raster branch, `"bokeh" in value.__module__` the bokeh branch, and everything else goes through value.to_json() with type 'altair' or 'plotly'. The raster branch calls processing_utils.encode_plot_to_base64(value, self.format), which renders through matplotlib's Agg canvas and returns the data: URL you saw. Then, since 6.18.0, it calls plt.close(value) on Figure instances — I watched plt.get_fignums() go from [1] to [] across one postprocess call. The result travels as PlotData(type=..., plot=<string>), a two-field pydantic model, and the frontend switches on type: <img src=data:...> for matplotlib, Plotly.newPlot for plotly, vega-embed for altair, Bokeh.embed for bokeh. That is also why a plot used as an input validates to PlotData: the browser sends back {type, plot}, so a bare base64 string from a client is rejected with 'Input should be a valid dictionary or instance of PlotData'.
Fun facts
Pros & cons
pros
- + Four plotting libraries behind one output slot — matplotlib, plotly, altair and bokeh — with the type sniffed from the object you return.
- + The plotly/altair path gives hover, drag-zoom, box select and PNG export for free in the corner modebar; no gr.Image, no caching, no savefig.
- + The matplotlib path is genuinely small: 7,031 base64 characters for a 5x3 chart where the same figure as png is 20,850 — cheap enough to redraw on a 2 s timer.
cons
- − A matplotlib figure is a bitmap: no hover, no zoom, no legend toggling, and it does not scale with the column — figsize x dpi is the final word on its size.
- − Accessibility is an afterthought: the img alt is the hardcoded string "undefined plot visualising provided data", so screen-reader users get nothing about your data.
- − Mistakes surface at postprocess time, not at your return statement — return a path or an array and you get an AttributeError in the server log plus a featureless 'Error' toast in the UI.
Takeaways
- 1Return the figure object itself; gr.Plot does the encoding, and a saved PNG path is the one thing it cannot take.
- 2Pick matplotlib when the chart is small and static (7,031 chars as webp), plotly when the reader should hover, zoom or export a PNG.
- 3Build a fresh figure per request — gradio closes Figure instances after rendering since 6.18.0, so a module-level figure breaks on the second call.
- 4For a live chart use gr.Timer(2).tick(fn, None, plot); never .change() on the plot you write to, or you get a render loop.
- 5Pin figsize and dpi: the bitmap is figsize x 100 px and drawn 1:1, so layout knobs like scale and min_width move the box, not the chart.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
