Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Interfaces and Components

Dataframes and Plots

Show tables and charts in Gradio: Dataframe as input and output, built-in LinePlot, BarPlot and ScatterPlot, and the Matplotlib route. Learn the data shapes each one needs.

Many apps end in a table or a chart: a prediction history, a metrics curve, a sales summary. Gradio offers an editable Dataframe, native plot components (LinePlot, BarPlot, ScatterPlot) that take a pandas DataFrame, and a generic Plot that accepts a Matplotlib figure. This lesson shows when to use each and what shape of data they expect. Gradio code is read-only; the stand-ins run real pandas and Matplotlib so you can see the data.

Dataframe

Python
import gradio as gr
import pandas as pd

def totals(df):
    df["total"] = df["price"] * df["qty"]
    return df

demo = gr.Interface(
    fn=totals,
    inputs=gr.Dataframe(
        headers=["item", "price", "qty"],
        datatype=["str", "number", "number"],
        row_count=(2, "dynamic"),
        col_count=(3, "fixed"),
        label="Order",
    ),
    outputs=gr.Dataframe(label="With totals"),
)

The page shows an editable grid with the three headers, two empty rows, and an add-row control. datatype sets the type per column. By default your function receives a pandas DataFrame (type="pandas"); "numpy" and "array" give an array or a list of lists. Users can paste from a spreadsheet, edit cells and sort columns. Empty cells appear as NaN or None, so clean the frame at the top of your function.

As an output, return a DataFrame (the header row comes from df.columns) or a list of lists plus headers=. Large tables should be capped with max_height or pagination options so the browser stays responsive.

Native plots

Since version 4, Gradio draws charts itself from a DataFrame:

Python
gr.LinePlot(value=df, x="day", y="sales", title="Sales")
gr.BarPlot(value=df, x="region", y="sales", color="region")
gr.ScatterPlot(value=df, x="weight", y="mpg", color="origin")

You name the columns for x, y and (optionally) color. The page shows an interactive chart with axes, a legend and tooltips. As outputs, the function returns the DataFrame, and the plot redraws. Important rules:

  • Data should be long (tidy): one row per point, with a color column naming the series. If your data is wide (one column per series), melt it first.
  • Dates should be real datetime values (or ISO strings parsed to dates), not labels like "Mon", or the axis order may be wrong.
  • Use x_title, y_title, height and tooltip for readability, and x_lim or y_lim to fix axis ranges.

These components are shaped like the built-in charts of Streamlit, so the long versus wide advice is the same.

Matplotlib and other libraries with gr.Plot

For anything the native plots do not draw (histograms, heatmaps, subplots), build a figure and return it:

Python
import matplotlib.pyplot as plt

def histogram(values, bins):
    fig, ax = plt.subplots()
    ax.hist(values, bins=int(bins))
    return fig

gr.Interface(histogram, [gr.Dataframe(), gr.Slider(2, 30, value=10)], gr.Plot())

gr.Plot accepts Matplotlib figures, Plotly figures and Altair charts. It renders the chart as an image or interactive object. Two practical rules for Matplotlib: create a new figure per call (global plt.plot state leaks between users) and close figures you no longer need (plt.close(fig)) to avoid memory growth in a long-lived server.

Need Use
Editable table, user data in Dataframe
Quick line, bar or scatter from a DataFrame LinePlot, BarPlot, ScatterPlot
Histograms, heatmaps, subplots Plot with Matplotlib
Interactive zoom with Plotly Plot with Plotly

Stand-in 1: clean a pasted table

Spreadsheet pastes bring empty rows, text numbers and stray spaces. This stand-in runs real pandas on what a Dataframe input would give you.

Python Stand-in: cleaning a Dataframe input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The half-empty third row is dropped, which is what you want rather than a NaN crash.

Stand-in 2: long data and a Matplotlib figure

Python Stand-in: tidy data and a figure per call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed table is the long format that a native LinePlot wants; the figure is what a gr.Plot output would display.

Practical tips

  • Show a table and a chart for the same result when users need exact numbers.
  • Offer a download: a gr.File output with a CSV (df.to_csv(path)) lets people take the data away.
  • Round numbers in the DataFrame before display, since long decimals make tables hard to read.
  • Keep the data small: sending 100,000 rows to the browser makes the page slow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does gr.Dataframe give your function by default?

    type="pandas" is the default; numpy and array forms are options.
  2. 2. Which data shape suits LinePlot with color="region"?

    Native plots expect tidy data, one row per point.
  3. 3. Why create a new Matplotlib figure for every call?

    All users share one Python process, so reusing a global figure mixes their results.
  4. 4. Which component renders a Matplotlib figure?

    gr.Plot accepts Matplotlib, Plotly and Altair figures.

Summary

  • Dataframe is an editable table; clean pasted data in your function.
  • LinePlot, BarPlot and ScatterPlot take tidy DataFrames and column names.
  • gr.Plot shows Matplotlib, Plotly or Altair figures; make a new figure per call.
  • Keep tables small and offer a CSV download for big results.

Next: Blocks Basics