Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 42 ยท Getting Started

Data for Plotly Charts

Prepare data for Plotly: lists, NumPy arrays, DataFrames, tidy versus wide format, melt and pivot, dates, category order, missing values and the built-in sample datasets.

Good charts start with well-shaped data. Plotly accepts plain Python lists, NumPy arrays, pandas Series and DataFrames (and, through the narwhals layer, other DataFrame libraries such as Polars). The same chart can usually be made from any of these, but the shape of the table decides how easy it is.

This lesson explains the shapes Plotly likes, how to convert between them with pandas, and how to handle dates, categories, missing values and big data. If you need a refresher on pandas itself, see the pandas tutorial.

Plain lists and arrays

Graph objects accept any sequence for x and y. Plotly converts lists to tuples and keeps NumPy arrays as arrays:

Python
import numpy as np
import plotly.graph_objects as go

x = np.linspace(0, 6.28, 50)
fig = go.Figure(go.Scatter(x=x, y=np.sin(x)))

Express accepts them too (px.line(x=x, y=np.sin(x))), but axis titles then become just x and y. DataFrames give you readable titles for free, because the column names are used.

Tidy (long) data versus wide data

The most important concept is the shape of the table.

Wide: one row per x value, one column per series.

month tea coffee
Jan 3 5
Feb 4 7

Long (tidy): one row per observation, with a column telling which series it belongs to.

month drink cups
Jan tea 3
Jan coffee 5
Feb tea 4
Feb coffee 7

Express works best with long data: px.line(long, x="month", y="cups", color="drink"). The column drink becomes the color, so the legend, trace names and hover text all come from your data. Adding a third drink means adding rows, not changing code.

Python Wide to long with melt, and back with pivot

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.

When you give Express wide data, it quietly melts it into two helper columns named variable and value. That explains the legend title variable and the axis title value. Rename them with labels={"variable": "Drink", "value": "Cups"} or melt the data yourself, as above.

The built-in sample datasets

plotly.express.data contains small datasets for learning. They return pandas DataFrames, so they are perfect for experiments. These are used throughout this course:

Call Content
px.data.iris() 150 flowers, 3 species, 4 measurements
px.data.tips() 244 restaurant bills with tip, day, time, smoker
px.data.gapminder() Country statistics by year (life expectancy, GDP, population)
px.data.stocks() Weekly relative stock prices (wide format, 105 rows)
px.data.wind() Wind frequency by direction and strength
px.data.election() Votes in a Montreal election, by district
px.data.medals_long() / medals_wide() Olympic medals in long and wide form
px.data.carshare() Car-sharing locations (lat/lon)
Python Explore the sample datasets

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.

Dates and times

Plotly detects real date columns and gives them a date axis with a sensible tick format, zoom and range selectors. Text that only looks like a date is treated as a category, so convert with pandas first:

Python
df["date"] = pd.to_datetime(df["date"])
Python Dates as a real date axis

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.

In the browser, plotly.js decides whether a string axis is a date, a number or a category by looking at the values. ISO strings (2025-03-01) are recognised as dates, but to avoid surprises convert to real datetimes and set xaxis.type explicitly if the chart ever looks wrong.

Category order and missing values

By default categories appear in the order they first occur in the data. Control it with category_orders (Express) or categoryorder (axis):

Python
fig = px.bar(df, x="size", y="count",
             category_orders={"size": ["S", "M", "L", "XL"]})

Missing values (NaN, None) are skipped. In line charts a missing value creates a gap; set connectgaps=True on the trace to bridge it. Drop or fill missing values in pandas (dropna, fillna) when you want a different result.

Python Category order and missing values

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.

Big datasets

SVG charts become slow with tens of thousands of points. For large scatter and line charts, use WebGL traces: px.scatter(..., render_mode="webgl") or go.Scattergl. They draw on the graphics card and handle hundreds of thousands of points. Another approach is to aggregate first (groupby, resample, a histogram instead of a scatter of raw values), because nobody can read 500,000 dots anyway.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which table shape does Plotly Express prefer when you want colors, facets and legends?

    With long data, color="column" creates traces, legend entries and hover text from your data automatically.
  2. 2. Which pandas method turns a wide DataFrame into a long one?

    melt unpivots columns into rows; pivot does the opposite.
  3. 3. What happens to a missing value (NaN) in a line chart?

    Missing points are skipped, which leaves a gap in the line. connectgaps=True joins the neighbours.
  4. 4. Which option helps a scatter plot with 200,000 points stay responsive?

    WebGL traces draw on the GPU instead of creating an SVG element per point.
  5. 5. How do you force the order S, M, L, XL on a bar chart's x axis in Express?

    category_orders maps a column name to the list of values in the desired order.

Summary

  • Plotly accepts lists, arrays, Series and DataFrames; DataFrames give readable titles.
  • Prefer long (tidy) data; use melt to reshape wide tables and pivot to go back.
  • px.data.* provides ready-made sample datasets.
  • Convert date text with pd.to_datetime so the axis is a real date axis.
  • Use category_orders for category order, remember gaps for missing values, and switch to WebGL or aggregate for big data.

Next: Show, Save and Export Figures