Interactive Graphics with Plotly (Python)

Download this Jupyter notebook:
Click here to download the .ipynb file
(Or use the “Download” button in the top right of the page if available.)

Part 1: Getting Started

What is Plotly?

  • An open-source library for interactive charts, built on the JavaScript library plotly.js
  • The same engine powers Plotly for Python, R, and Julia, so the charts look and behave the same everywhere
  • Every figure is a small web page: hover, zoom, pan, and download come for free
  • Figures render inside notebooks, Quarto documents, and standalone HTML files
  • Two Python interfaces:
    • plotly.express (px): one function call per chart, works directly on data frames
    • plotly.graph_objects (go): build a figure trace by trace for full control
  • Install with conda install plotly or pip install plotly

The Gapminder data

  • Life expectancy, population, and GDP per capita for 142 countries
  • Measured every 5 years from 1952 to 2007 (1,704 rows)
  • Columns: country, continent, year, lifeExp, pop, gdpPercap
  • Ships with Plotly as px.data.gapminder(), which also includes ISO country codes for maps
Code
import plotly.io as pio
pio.renderers.default = "plotly_mimetype+notebook_connected"
Code
import plotly.express as px

df = px.data.gapminder()

print(df.shape)
df.head()
(1704, 8)
country continent year lifeExp pop gdpPercap iso_alpha iso_num
0 Afghanistan Asia 1952 28.801 8425333 779.445314 AFG 4
1 Afghanistan Asia 1957 30.332 9240934 820.853030 AFG 4
2 Afghanistan Asia 1962 31.997 10267083 853.100710 AFG 4
3 Afghanistan Asia 1967 34.020 11537966 836.197138 AFG 4
4 Afghanistan Asia 1972 36.088 13079460 739.981106 AFG 4

Your first interactive plot

  • One call maps data columns to the x and y axes
  • Try the built-in interactions:
    • Hover over a point to see its values
    • Drag to zoom into a region; double-click to reset
    • Use the toolbar (top right) to pan, zoom, or save a PNG
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp")
fig.show()

Part 2: Core Chart Types

Mapping more variables: color and size

  • Add a third and fourth variable with color and size
  • Categorical color produces one trace per group, plus a clickable legend
  • Click a legend entry to hide a group; double-click to isolate it
  • size_max sets the diameter, in pixels, of the largest bubble
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp",
                 color="continent", size="pop", size_max=60)
fig.show()

Line charts

  • Use lines for values that change over time
  • color draws one line per country
  • Hover over any point to compare countries in the same year
Code
import plotly.express as px

countries = ["United States", "China", "India", "Brazil", "Nigeria"]
df = px.data.gapminder().query("country in @countries")

fig = px.line(df, x="year", y="lifeExp", color="country", markers=True)
fig.show()

Bar charts

  • Summarize the data first, then plot one bar per category
  • Here: total population of each continent in 2007
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")
totals = df.groupby("continent", as_index=False)["pop"].sum()

fig = px.bar(totals, x="continent", y="pop")
fig.show()

Histograms

  • Show the distribution of a single numeric variable
  • Set the number of bins to control the level of detail
  • Hover over a bar to see its range and count
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.histogram(df, x="lifeExp", nbins=20)
fig.show()

Box plots

  • Compare distributions across groups
  • Showing every point alongside the box reveals the individual countries
  • Hover over a box to see its median, quartiles, and fences
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.box(df, x="continent", y="lifeExp", points="all")
fig.show()

Part 3: Customizing Figures

Titles, axis labels, and log scales

  • Replace raw column names with readable labels
  • A log scale spreads out data that spans several orders of magnitude, like GDP
  • In Plotly Express, most options are arguments to the plotting function
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
                 log_x=True,
                 title="Wealthier countries live longer (2007)",
                 labels={"gdpPercap": "GDP per capita (US$, log scale)",
                         "lifeExp": "Life expectancy (years)",
                         "continent": "Continent"})
fig.show()

Controlling the hover tooltip

  • The tooltip is often the most useful part of an interactive chart
  • Show the country name in bold, add extra columns, and format the numbers
  • hover_name sets the bold title; hover_data adds, hides, or formats columns
  • Format strings follow d3 rules: :, adds thousands separators, :.1f keeps one decimal
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
                 log_x=True, hover_name="country",
                 hover_data={"pop": ":,",
                             "gdpPercap": ":,.0f",
                             "lifeExp": ":.1f",
                             "continent": False})
fig.show()

Choosing colors

  • Assign a specific color to each category for consistency across charts
  • This palette (Okabe-Ito) stays distinguishable for colorblind readers
  • Colors can be given as names ("red") or hex codes ("#E69F00")
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

palette = {"Africa": "#E69F00", "Americas": "#56B4E9", "Asia": "#009E73",
           "Europe": "#CC79A7", "Oceania": "#0072B2"}

fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
                 color_discrete_map=palette, log_x=True)
fig.show()

Layout and styling

  • The layout controls everything that is not data: background, fonts, legend, size, margins
  • Here: a clean white background, a larger font, and a horizontal legend below the plot
  • fig.update_layout() changes layout settings after the figure is created; template applies a complete built-in theme
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
                 log_x=True)

fig.update_layout(template="plotly_white",
                  font=dict(size=14),
                  height=450,
                  legend=dict(orientation="h", y=-0.25))
fig.show()

Part 4: Going Further

Faceting: small multiples

  • Split one chart into a panel per group to reduce overplotting
  • Panels share the y-axis, so they are easy to compare
  • facet_col creates one column per continent; the last line shortens the panel titles
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp",
                 facet_col="continent", log_x=True)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.show()

Animation

  • Add a time dimension: each year becomes one frame
  • Press play or drag the slider; Plotly smoothly moves each country between frames
  • Fix the axis ranges so the axes do not jump between frames
  • animation_frame sets the frames; animation_group tells Plotly which marker is the same country across frames
Code
import plotly.express as px

df = px.data.gapminder()

fig = px.scatter(df, x="gdpPercap", y="lifeExp",
                 animation_frame="year", animation_group="country",
                 size="pop", color="continent", hover_name="country",
                 log_x=True, size_max=55,
                 range_x=[100, 100000], range_y=[25, 90])
fig.show()

Choropleth maps

  • Color each country by a value; three-letter ISO codes tell Plotly which shape to fill
  • A continuous variable gets a color scale and a colorbar instead of a legend
  • Scroll to zoom and drag to pan the map
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.choropleth(df, locations="iso_alpha", color="lifeExp",
                    hover_name="country",
                    color_continuous_scale="Viridis",
                    projection="natural earth")
fig.show()

Building a figure layer by layer

  • For full control, start from an empty figure and add one trace at a time
  • Each trace can have its own data, style, and legend name
  • Annotations and reference lines add context to the story
  • This uses plotly.graph_objects, the low-level interface that Plotly Express is built on
Code
import plotly.express as px
import plotly.graph_objects as go

df = px.data.gapminder()
us = df[df["country"] == "United States"]
cn = df[df["country"] == "China"]
world = df.groupby("year", as_index=False)["lifeExp"].mean()
dip = cn.loc[cn["year"] == 1962, "lifeExp"].iloc[0]

fig = go.Figure()
fig.add_trace(go.Scatter(x=us["year"], y=us["lifeExp"],
                         mode="lines+markers", name="United States"))
fig.add_trace(go.Scatter(x=cn["year"], y=cn["lifeExp"],
                         mode="lines+markers", name="China"))
fig.add_trace(go.Scatter(x=world["year"], y=world["lifeExp"],
                         mode="lines", name="World average",
                         line=dict(dash="dash", color="gray")))
fig.add_annotation(x=1962, y=dip, text="Dip after the 1959-61 famine",
                   showarrow=True, arrowhead=2, ax=40, ay=40)
fig.update_layout(xaxis_title="Year", yaxis_title="Life expectancy (years)")
fig.show()

Range sliders

  • A range slider below the x-axis lets readers focus on a time window
  • Drag the handles to zoom; drag the shaded window to pan through time
Code
import plotly.express as px

countries = ["United States", "China", "India", "Brazil", "Nigeria"]
df = px.data.gapminder().query("country in @countries")

fig = px.line(df, x="year", y="gdpPercap", color="country")
fig.update_xaxes(rangeslider_visible=True)
fig.show()

Saving and sharing

  • Save any figure as a standalone HTML file that keeps all of its interactivity
  • Open the file in a browser, email it, or embed it in a website
  • For a static image, use the camera icon in the toolbar
  • include_plotlyjs="cdn" keeps the file small by loading plotly.js from the web; use True for a fully offline file
Code
import plotly.express as px

df = px.data.gapminder().query("year == 2007")

fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
                 hover_name="country", log_x=True)

fig.write_html("gapminder_2007.html", include_plotlyjs="cdn")
print("Saved gapminder_2007.html")
Saved gapminder_2007.html

Wrap-Up

Summary: Python and R side by side

Task Python (plotly.express) R (plotly)
Scatter px.scatter(df, x=, y=) plot_ly(df, x = ~, y = ~, type = "scatter")
Line px.line() mode = "lines"
Bar px.bar() type = "bar"
Histogram px.histogram() type = "histogram"
Box px.box() type = "box"
Color, size color=, size= color = ~, size = ~
Hover text hover_name=, hover_data= text = ~, hovertemplate =
Log axis log_x=True layout(xaxis = list(type = "log"))
Layout fig.update_layout() layout()
Facets facet_col= subplot()
Animation animation_frame= frame = ~
Map px.choropleth() type = "choropleth"
Add a layer fig.add_trace() add_trace()
Save fig.write_html() htmlwidgets::saveWidget()