# Gradio for Charts: Turn a Plotting Function into a Web App

> Build a chart app with Gradio. Wrap a Matplotlib function in gr.Interface, return Plotly figures from gr.Blocks, and use gr.LinePlot and gr.BarPlot with a DataFrame.

Source: https://www.pythoncharts.com/python/gradio-chart-app/ | Published: 2026-12-06 | Author: Alex Scott | Category: Python | Tags: gradio, dashboard, interactive, matplotlib, plotly, web-app

To put a chart in a web page with Gradio, write a function that returns a Matplotlib or Plotly figure, then wrap it with `gr.Interface(fn, inputs, outputs=gr.Plot())` and call `.launch()`. Gradio builds the form, runs your function when the inputs change and shows the figure. It was made for machine learning demos, but a plotting function is just another function. For a side-by-side with other app frameworks, see [Streamlit vs Dash vs Shiny vs Gradio vs Panel](https://www.pythoncharts.com/python/streamlit-vs-dash-vs-shiny-vs-gradio-vs-panel/).

This post uses Gradio 6.32 (`pip install gradio`) and a simulated data set: rides per hour at four bike-share stations. The apps are complete files. Save one as `app.py`, run `python app.py`, and open `http://127.0.0.1:7860`.

## Quick Example

```python
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(31)
hours = np.arange(24)
STATIONS = ["Harbor", "University", "Old Town", "Airport"]
COLORS = {"Harbor": "#2a6f97", "University": "#e07a5f", "Old Town": "#6a994e", "Airport": "#7b4b94"}

def peak(center, width, height):
    return height * np.exp(-((hours - center) ** 2) / (2 * width**2))

rides = pd.DataFrame(
    {
        "Harbor": peak(8, 1.5, 90) + peak(17.5, 1.8, 110) + peak(13, 3, 40),
        "University": peak(9, 1.5, 140) + peak(15, 2, 80) + peak(21, 2, 70),
        "Old Town": peak(12.5, 3, 100) + peak(19, 2, 120),
        "Airport": peak(6, 2, 60) + peak(14, 3, 45) + peak(22, 2.5, 55),
    },
    index=pd.Index(hours, name="Hour"),
)
rides = (rides + rng.normal(0, 6, rides.shape)).clip(lower=0).round()

def plot_station(station, smooth):
    smoothed = rides[station].rolling(smooth, center=True, min_periods=1).mean()
    fig, ax = plt.subplots(figsize=(7, 4))
    ax.plot(rides.index, rides[station], color="#c9c9c9", label="Raw")
    ax.plot(smoothed.index, smoothed, color=COLORS[station], linewidth=2.5, label=f"{smooth}-hour average")
    ax.set_xlabel("Hour of day")
    ax.set_ylabel("Rides")
    ax.set_xticks(range(0, 24, 3))
    ax.legend(frameon=False, loc="upper center")
    fig.tight_layout()
    return fig

demo = gr.Interface(
    fn=plot_station,
    inputs=[
        gr.Dropdown(STATIONS, value="Harbor", label="Station"),
        gr.Slider(1, 7, value=3, step=2, label="Smoothing window (hours)"),
    ],
    outputs=gr.Plot(label="Rides per hour"),
    title="Bike-share rides by hour",
    flagging_mode="never",
)
demo.launch()
```

![Gradio app with a station dropdown and smoothing slider on the left and a line chart of rides per hour on the right](https://www.pythoncharts.com/python/gradio-chart-app/images/gradio-quick-example.png)

`gr.Interface` takes three things: the function, a list of input components (one per function argument, in order) and an output component. The dropdown value arrives as `station`, the slider value as `smooth`, and whatever the function returns goes to `gr.Plot`. Press **Submit** to run it. Harbor has a morning bump and a bigger evening peak: with a 3-hour average, the busiest hour is 17:00 at 112 rides.

## How do I make the chart update without a Submit button?

Add `live=True` and Gradio reruns the function every time an input changes. `examples=` adds clickable rows of inputs below the form:

```python
demo = gr.Interface(
    fn=plot_station,
    inputs=[
        gr.Dropdown(STATIONS, value="Harbor", label="Station"),
        gr.Slider(1, 7, value=3, step=2, label="Smoothing window (hours)"),
    ],
    outputs=gr.Plot(label="Rides per hour"),
    live=True,
    examples=[["University", 1], ["Airport", 5]],
    flagging_mode="never",
)
demo.launch()
```

## How do I lay out several charts and a table with gr.Blocks?

`gr.Interface` is a fixed form-then-output layout. For anything else, use `gr.Blocks`, which lets you place components in `gr.Row`, `gr.Column` and `gr.Tab` and wire up events yourself. This version replaces the dropdown with a checkbox group, returns a Plotly figure and fills a `gr.Dataframe` with each station's busiest hour. It reuses the data setup from the Quick Example, so only the new part is shown:

```python
import plotly.express as px

def update(selected, smooth):
    smoothed = rides[selected].rolling(smooth, center=True, min_periods=1).mean()
    fig = px.line(smoothed, color_discrete_map=COLORS, labels={"value": "Rides", "variable": "Station"})
    fig.update_layout(margin=dict(t=20), legend_title_text="")
    busiest = pd.DataFrame(
        {
            "Station": selected,
            "Busiest hour": [f"{smoothed[s].idxmax()}:00" for s in selected],
            "Rides": [round(smoothed[s].max()) for s in selected],
        }
    )
    return fig, busiest

with gr.Blocks(title="Bike-share rides") as demo:
    gr.Markdown("## Bike-share rides by hour")
    with gr.Row():
        with gr.Column(scale=1, min_width=240):
            stations = gr.CheckboxGroup(STATIONS, value=["Harbor", "University"], label="Stations")
            smooth = gr.Slider(1, 7, value=3, step=2, label="Smoothing window (hours)")
        with gr.Column(scale=3):
            chart = gr.Plot(label="Rides per hour")
            table = gr.Dataframe(label="Busiest hour")
    gr.on(
        triggers=[demo.load, stations.change, smooth.change],
        fn=update,
        inputs=[stations, smooth],
        outputs=[chart, table],
    )

demo.launch()
```

![Gradio Blocks app with a checkbox group and slider on the left, an interactive Plotly line chart of two stations and a table of each station's busiest hour](https://www.pythoncharts.com/python/gradio-chart-app/images/gradio-blocks-dashboard.png)

`gr.on()` attaches one function to several triggers. `demo.load` fires when the page opens, so the chart is drawn before anyone touches a control. With the default stations, University peaks at 9:00 (123 rides) and Harbor at 17:00 (112). The function returns two values, which go to the two components listed in `outputs`, in order. The returned DataFrame fills the table. Plotly figures stay interactive inside `gr.Plot` (hover, zoom, legend clicks). Matplotlib figures arrive as images.

## Can Gradio draw charts without Matplotlib or Plotly?

Yes. `gr.LinePlot`, `gr.BarPlot` and `gr.ScatterPlot` take a pandas DataFrame and the names of the x, y and color columns. They need a long-format table with one row per observation, so melt the wide table first:

```python
long = rides.reset_index().melt(id_vars="Hour", var_name="Station", value_name="Rides")

with gr.Blocks() as demo:
    gr.LinePlot(
        long, x="Hour", y="Rides", color="Station", color_map=COLORS,
        title="Rides by hour", height=300,
    )
    gr.BarPlot(
        long, x="Station", y="Rides", y_aggregate="sum",
        y_lim=[0, 1500], title="Total rides per station", height=300,
    )

demo.launch()
```

![Two native Gradio charts: a line chart of rides by hour for four stations and a bar chart of total rides per station](https://www.pythoncharts.com/python/gradio-chart-app/images/gradio-native-plots.png)

Old Town has the most rides (1,357 of 4,595) and Airport the fewest (862). `y_lim=[0, 1500]` starts the bars at zero. Without it Gradio picked a lower limit near 860 for this data, which made the Airport bar look tiny. The `y_aggregate` argument collapses repeated x values with `"sum"`, `"mean"`, `"median"`, `"min"`, `"max"` or `"count"`. The native plots need no figure object. They have fewer options than Matplotlib or Plotly, so use them for simple charts and a figure for anything else.

## How do I share the app or run it on a server?

`demo.launch()` takes the options you will want when the app leaves your laptop:

```python
demo.launch(
    server_name="0.0.0.0",  # listen on all network interfaces, not just localhost
    server_port=8080,       # default is 7860
    share=True,             # temporary public https://*.gradio.live link
)
```

`share=True` opens a tunnel and prints a temporary public URL, so anyone with the link can use the app while your process runs. Leave it off unless you mean that. For a permanent URL, run it on your own server or host it on a Hugging Face Space.

## Gradio vs Streamlit vs Dash for chart apps

| | Gradio | Streamlit | Dash |
|---|---|---|---|
| Model | Function in, output out | Script reruns top to bottom | Explicit callbacks |
| Fastest start | `gr.Interface(fn, inputs, outputs)` | `st.slider(...)` in a script | Layout plus `@callback` |
| Layout control | `Blocks`, `Row`, `Column`, `Tab` | Sidebar, columns, tabs | Full HTML and CSS |
| Best for | A function with a few inputs, model demos | Data exploration apps | Dashboards with many linked charts |

Pick Gradio when the app is a function with a handful of inputs and an output, especially when other outputs (images, audio, text from a model) sit beside the chart. For dashboards with many linked views, [Dash](https://www.pythoncharts.com/plotly/dash-callbacks/) or [Streamlit](https://www.pythoncharts.com/streamlit/streamlit-python-guide/) give you more control.

## Practical Tips

- **Function arguments follow component order.** `inputs=[a, b]` calls `fn(a_value, b_value)`. Labels do not matter, position does.
- **Return the figure, not `plt.show()`.** `gr.Plot` displays the object your function returns.
- **`live=True` does not run the function on page load.** The plot area stays empty until an input changes or an example is clicked. In `gr.Blocks`, add `demo.load` to the triggers (as above) to draw a first chart.
- **Set `flagging_mode="never"`** on `gr.Interface` to leave out the Flag button, which is meant for collecting feedback on model outputs.
- **Set the axis range on native plots** (`y_lim=`) when bars are involved. Gradio's automatic range may not start at zero.

## Similar Topics

- [Streamlit vs Dash vs Shiny vs Gradio vs Panel](https://www.pythoncharts.com/python/streamlit-vs-dash-vs-shiny-vs-gradio-vs-panel/)
- [Shiny for Python: A Reactive Dashboard](https://www.pythoncharts.com/python/shiny-for-python-dashboard/)
- [Dash Callbacks: Chained Dropdowns, Pattern-Matching, Store and Clientside](https://www.pythoncharts.com/plotly/dash-callbacks/)
