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