Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 31 ยท Plotly

Plotly Express Basics

Draw line, bar and scatter charts from a pandas DataFrame with Plotly Express, and see the figure JSON behind them with a runnable Python stand-in.

Plotly Express, imported as px, is the quickest way to get an interactive chart out of Python. You hand it a table and tell it which columns to use, and one function call returns a complete figure with axes, a legend, hover tooltips, zoom and pan already working. It is the first thing most people learn in Plotly, and for most everyday charts it is also the last thing they need.

The Plotly library itself needs Python, a browser and a package install, so it cannot run on this site. The Plotly code below is read-only. The runnable examples are stand-ins: they use pandas in the in-browser Python runner to build the same JSON description that Plotly Express produces, so you can see exactly what one px call creates. Real Plotly output has many more keys than the stand-in, and the stand-in says so wherever it matters. If you have not yet seen how a chart is assembled, read How a Chart Works Inside first.

One call, one figure

A DataFrame Tidy rows and named columns.
Column names x, y, color, size say what to draw.
A figure Traces, layout, hover, zoom.

Express maps columns to visual channels for you.

1 / 2

Your first chart

Install the library with pip install plotly pandas. Then build a small DataFrame and pass it to px.line. This is read-only code:

Python
import pandas as pd
import plotly.express as px

sales = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "units": [120, 150, 90, 180, 140, 110],
})

fig = px.line(sales, x="month", y="units", markers=True,
              title="Units sold per month")
fig.show()

fig.show() opens the chart in your notebook, or in a browser tab when you run a plain script. The chart is interactive straight away: hovering shows a tooltip for each point, dragging zooms into a region, double-clicking resets the view, and the toolbar in the corner can download a PNG.

Notice what you did not write: no axis labels, no tick calculations, no colors. Express reads the column names and uses them as axis titles (month, units). Its decisions come from the data, not from separate styling code.

The three workhorse functions

Almost every Express function follows the same pattern: px.something(data_frame, x=..., y=..., color=..., ...). The arguments are column names (strings), not lists of numbers, which is why a tidy table matters so much (see Preparing Data: Tidy Format and Reshaping).

Python
long = pd.DataFrame({
    "month":  ["Jan", "Feb", "Mar", "Jan", "Feb", "Mar"],
    "region": ["North", "North", "North", "South", "South", "South"],
    "units":  [120, 150, 90, 80, 95, 130],
})

# One line per region, each with its own color and legend entry
px.line(long, x="month", y="units", color="region")

# Bars side by side; barmode="group" is the other common choice to "stack"
px.bar(long, x="month", y="units", color="region", barmode="group")

# Points for a relationship between two numeric columns
px.scatter(long, x="month", y="units", color="region", size="units")

The color argument is the key idea. When you give it a column with several values, Express does not draw one trace: it splits the data by that column and draws one trace per value, each with its own color and a legend entry. The same trick works for size (point area), symbol (marker shape) and, for bars, pattern_shape. For small multiples there is facet_col and facet_row, which split the data into a grid of panels.

Function Best for Typical arguments
px.line Trends over an ordered axis such as time x, y, color, markers
px.bar Comparing values across categories x, y, color, barmode, orientation
px.scatter Relationships between two numbers x, y, color, size, trendline
px.histogram The distribution of one number x, nbins, color
px.pie A few parts of a whole names, values

When a chart looks wrong, check the data before the chart call. A wide table (one column per region) usually needs reshaping to long format first, or Express cannot split it by color.

What a figure holds

px.line(...) returns a plotly.graph_objects.Figure. That object is a thin wrapper around two plain structures: data, a list of traces (one per line, bar group or scatter series), and layout, which controls everything that is not a trace, such as the title and axes. You can print the whole thing with fig.to_dict() or fig.to_json(). The exact layout of those two parts is the topic of Plotly Figures: Data, Layout and Traces.

Express does the following work for you each time:

  1. Reads the columns you named.
  2. Splits the rows into groups when you give color, symbol or facet_*.
  3. Creates one trace per group, with the right trace type (scatter, bar, ...).
  4. Fills in axis titles, legend titles and a hover template.
  5. Returns the figure, ready to show or save.

Here is a stand-in that does steps 1 to 3 with pandas and prints the result as JSON. It is not Plotly: the real figure has dozens of defaults (template, colorway, margins, hover templates) that this stand-in leaves out. But the core, a list of traces whose x and y arrays come from groups of rows, is the same.

Python Turn a DataFrame into figure JSON

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 output shows two traces, named North and South, each with its own x and y lists. That is the whole secret of the color argument: one group of rows becomes one trace. Change "line" to "bar" and the trace type changes to bar and the mode key disappears, because bars have no drawing mode.

Showing, saving and tuning

A figure is just an object, so what you do with it is a separate step. These calls are read-only here:

Python
fig.show()                       # notebook, or a browser tab from a script
fig.write_html("sales.html")     # a standalone, interactive page
fig.write_html("sales.html", include_plotlyjs="cdn")  # smaller file, needs internet
fig.update_layout(title="New title", yaxis_title="Units")
fig.update_traces(line_width=3)

write_html is how you share an interactive chart without any server: the file contains the data and the plotly.js library (about 3.5 MB unless you load it from a CDN), and any browser can open it. update_layout and update_traces change a finished figure, which is how you fine-tune Express output. Larger styling work is covered in Plotly Styling, Templates and Annotations. Exporting to static images and embedding pages is in Exporting, Embedding and Sharing Charts.

Built-in help from the data

Express also does small pieces of analysis for you. Pass trendline="ols" to px.scatter to add a fitted line (this needs the statsmodels package), or text_auto=True to px.bar to print each value on its bar. Express sample datasets such as px.data.gapminder() and px.data.tips() ship with the library, which makes them handy for trying a call without preparing a file.

A closer look at splitting

The next stand-in shows how color, grouping and a missing value interact. A common surprise is that a column with a missing category value silently drops those rows from the split. The code counts rows per trace so you can see it.

Python How many rows land in each trace?

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.

Five of the six rows are drawn and the sixth vanishes without any error. Whenever a chart seems to be missing points, count the rows per group like this before you blame the library.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In px.line(df, x="month", y="units", color="region"), what do the arguments x, y and color refer to?

    Express takes column names as strings and reads the values from the DataFrame. That is why the data should be tidy.
  2. 2. What does the color argument do when the column has three different values?

    Each group of rows becomes one trace. This is the central idea of Express and what the stand-in reproduces with groupby.
  3. 3. Which call saves an interactive chart as a page anyone can open in a browser?

    write_html writes a standalone HTML file with the data and plotly.js. to_dict only returns a dictionary and update_layout changes the figure.
  4. 4. Why does the stand-in in this lesson not count as real Plotly?

    A real figure carries a template, colorway, hover templates and more. The stand-in shows the core structure only.

Summary

  • Plotly Express turns a tidy DataFrame and column names into a full interactive figure with one call.
  • Pick px.line for trends, px.bar for category comparisons and px.scatter for relationships.
  • color, symbol, size and facet_* split or encode data: one group of rows becomes one trace.
  • The result is a Figure made of data (traces) and layout; show, write_html, update_layout and update_traces work on it.
  • Rows with a missing group value can silently disappear from a split chart.
  • The Plotly calls here are read-only; the pandas code is a stand-in for the figure structure.

Next: Plotly Figures: Data, Layout and Traces.