Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 76 ยท Visualization and Storytelling

Interactive Charts with Plotly: Scatter, Bar, Line, Animation and Maps

Build quick interactive charts with Plotly Express: scatter, bar, line, animated and choropleth maps, and see the figure data behind each call with runnable Python stand-ins.

Static charts from Matplotlib and Seaborn are perfect for reports. Sometimes, though, the reader needs to explore: hover to see the exact value, zoom into a crowded corner, switch a category on and off, or press play to watch a trend unfold. Plotly produces charts like that from a few lines of Python, and its plotly.express module (usually imported as px) is built for the quick, one-call chart an analyst wants.

This lesson shows the five chart types analysts reach for first (scatter, bar, line, animation and choropleth map), when interactivity helps, and when it does not. The full Plotly story, including styling and dashboards, is in the Data Visualization track.

Plotly needs its own JavaScript library to draw, so it cannot run on this page. The Plotly code blocks are read-only. Each one is followed by a runnable stand-in that uses pandas to build the same kind of data structure Plotly creates (a figure is just a dictionary of traces and layout), so you can see what one px call really produces. Real Plotly figures contain many more keys than the stand-ins.

One call, one interactive chart

Every Plotly Express function takes a tidy DataFrame and column names. The result is a figure with axes, legend, hover tooltips, zoom, pan and a download button already working.

Python
# Read-only: needs the plotly package and a notebook or browser to display
import plotly.express as px

fig = px.scatter(df, x="spend", y="visits", color="segment",
                 size="orders", hover_name="customer", title="Visits against spend")
fig.show()

Notice the mapping: columns to visual channels. color splits the points by a category, size scales the markers by a number, and hover_name sets the bold title of the tooltip. Compare it with sns.scatterplot in Seaborn for Analysts: the idea is the same, the output is interactive.

Python Stand-in: what px.scatter builds

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 legend of the real chart is simply this list of traces: clicking an entry hides that trace. That is the interactivity you get for free.

Bar and line charts

px.bar compares categories and px.line follows a value over an ordered axis. Both take color to split into groups, and barmode="group" puts the bars side by side instead of stacking them.

Python
# Read-only
fig = px.bar(sales, x="region", y="revenue", color="quarter", barmode="group")
fig = px.line(daily, x="date", y="visitors", color="channel", markers=True)

For line charts, remember that the order of the rows matters: sort by the x column first, or the line will zig-zag. And do not draw a line between categories that have no natural order; use bars.

Python Stand-in: grouped bars and sorted lines

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.

Animation: change over time

Pass a column to animation_frame and Plotly adds a play button and a slider. Each value of that column becomes one frame; the chart morphs between frames. It suits a few variables changing over time, such as income and life expectancy by year. To keep the axes steady while the data moves, set range_x and range_y, otherwise the axes jump and the animation becomes hard to follow.

Python
# Read-only
fig = px.scatter(df, x="gdp_per_person", y="life_expectancy", size="population",
                 color="continent", animation_frame="year", hover_name="country",
                 log_x=True, range_x=[300, 100000], range_y=[25, 90])
fig.show()
Python Stand-in: frames of an animation

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.

Maps: the choropleth

A choropleth colours regions (countries, states, districts) by a value. Plotly can draw world countries from their ISO-3 codes ("PRT", "USA") without you supplying shapes; for other regions you provide a GeoJSON file and say which property matches your data.

Python
# Read-only
fig = px.choropleth(df, locations="iso3", color="internet_share",
                    hover_name="country", color_continuous_scale="Blues",
                    range_color=[0, 100])
fig.show()

The usual traps are joining on the wrong code (names such as "Czechia" versus "Czech Republic" do not match, ISO codes do), colouring raw counts that simply follow population (show rates or shares instead), and using a rainbow scale that hides the order of values. See Visualization Principles for the colour rules.

Python Stand-in: prepare and check data for a choropleth

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 interactive helps, and when it hurts

Interactive charts shine when the audience will explore: dashboards, web reports, internal tools, large scatter plots where hovering identifies points. They add little, and sometimes hurt, when:

  • the chart must work in a PDF, slide or printed page, where nothing can be hovered. Export a static image (fig.write_image, which needs the kaleido package) or use Matplotlib.
  • the message is one number or one trend. A clean static chart with a clear title communicates faster than something the reader has to operate.
  • the data are huge. Millions of points in the browser are slow; aggregate first.
  • accessibility matters: tooltips are not available to keyboard or screen reader users, so put the key numbers in text as well.

Whatever the tool, the rules of Visualization Principles and Communicating Results still apply: choose the chart by the question, label axes with units, and let a title state the finding.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the color argument of px.scatter do?

    Plotly Express maps the column to the color channel and creates one trace per distinct value, which also becomes a clickable legend entry.
  2. 2. Which argument adds a play button and slider that step through the values of a column?

    Each value of the animation_frame column becomes one frame of the animation.
  3. 3. A choropleth of raw case counts shows the biggest countries darkest. What is the best fix?

    Counts mostly follow population size. A rate or share lets regions be compared fairly.
  4. 4. In which situation is an interactive chart a poor choice?

    On paper nothing can be hovered or zoomed, so a static chart with the key numbers labelled works better.

Summary

  • Plotly Express turns a tidy DataFrame and column names into interactive charts: px.scatter, px.bar, px.line, px.choropleth, and animation_frame for animation.
  • A figure is a dictionary of traces and layout; color creates one trace per group, which powers the clickable legend.
  • Sort line data by x, fix axis ranges for animations and use rates, not raw counts, on maps.
  • Interactivity helps exploration and dashboards; for print, slides or one clear message, use a static chart.
  • Plotly code here is read-only; the stand-ins show the structure behind each call.

Next: Visualizing Distributions and Uncertainty.