Plotly Express: charts from a DataFrame

Plotly · Essentials · 10 min

Plotly Express is the fastest way to an interactive chart and covers most everyday plotting.

Plotly Express functions take a DataFrame and column names:

px.scatter(df, x="gdpPercap", y="lifeExp")
px.line(df, x="date", y="price")
px.bar(df, x="country", y="pop")

Each returns a complete Figure with axis titles taken from the column names, hover tooltips showing the mapped values, and a default theme. Display it with fig.show() in a notebook or script, or save it with fig.write_html(...).

Express accepts pandas DataFrames and, through the narwhals compatibility layer, also Polars and PyArrow tables. You can also pass plain lists or arrays: px.line(x=[1, 2, 3], y=[2, 4, 3]).

Common arguments shared by most functions:

  • title=, labels={"gdpPercap": "GDP per capita"} to rename columns in axis titles, legends and tooltips;
  • log_x=True / log_y=True, range_x=[0, 10];
  • width=, height= in pixels;
  • template="plotly_white" for a lighter look.

px.line connects points in the order of the rows, so sort by x first. With y=["a", "b"] (several columns) Express draws one trace per column from wide-form data.

px.data ships sample datasets (gapminder, tips, iris, stocks) bundled with the library, handy for experimenting offline.

Example

import plotly.express as px

df = px.data.gapminder().query("year == 2007")
print(df.shape)                              # (142, 8)

fig = px.scatter(df, x="gdpPercap", y="lifeExp", log_x=True,
                 labels={"gdpPercap": "GDP per capita",
                         "lifeExp": "Life expectancy"},
                 title="Wealth and health, 2007")
print(fig.layout.xaxis.title.text)           # GDP per capita
print(fig.layout.xaxis.type)                 # log
print(len(fig.data), fig.data[0].mode)       # 1 markers

stocks = px.data.stocks()
fig2 = px.line(stocks, x="date", y=["GOOG", "AAPL"])   # wide form
print([t.name for t in fig2.data])           # ['GOOG', 'AAPL']
fig.write_html("gapminder.html")

Remember

  • px functions take a DataFrame plus column names and return a Figure
  • labels= renames columns everywhere they appear
  • Passing several y columns draws one trace per column

Watch out for

  • Plotting unsorted data with px.line, which connects rows in their given order.

Check yourself

  1. What does `px.line(df, x='date', y=['open', 'close'])` produce?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: plotly.com/python/plotly-express/

Plotly Express: charts from a DataFrame · Plotly · Topolearn