DS Plotly Charts

Plotly is a Python library that draws interactive charts. Readers can hover over points to see values, zoom into a region, and click legend items to hide or show groups. Interactive charts invite exploration, and they work well on web pages and in notebooks.

A printed map shows one view. A digital map lets you zoom, drag, and tap places for details. Plotly gives charts that same freedom.

Install and Import

pip install plotly

import plotly.express as px
import pandas as pd

Plotly Express is the short-command interface. One line creates a full chart from a Pandas table.

Static versus Interactive

FeatureStatic ChartPlotly Chart
Hover detailsNoYes
Zoom and panNoYes
Hide groups with a clickNoYes
Export as an imageYesYes, via a toolbar button
Share as a web pageNeeds an imageSaves as an HTML file

Sample Data

df = px.data.gapminder()
print(df.head())

The gapminder dataset lists countries by year with population, life expectancy, and income per person. It makes a rich practice set.

Line Chart

india = df[df["country"] == "India"]
fig = px.line(india, x="year", y="lifeExp", title="Life Expectancy in India")
fig.show()

Hover over any point to read the exact year and value.

Bar Chart

latest = df[df["year"] == 2007]
top = latest.nlargest(10, "pop")
fig = px.bar(top, x="country", y="pop", color="continent")
fig.show()

Scatter Chart with Four Dimensions

fig = px.scatter(
    latest, x="gdpPercap", y="lifeExp",
    size="pop", color="continent",
    hover_name="country", log_x=True)
fig.show()
 lifeExp
   |                              O  O   (rich, long life)
   |                        O   O
   |                  o  o
   |            .  .
   |      .  .                   Dot position = two numbers
   |   .                         Dot size     = population
   +------------------------     Dot color    = continent
          gdpPercap (log scale)

One chart carries four pieces of information: income on the horizontal axis, life expectancy on the vertical axis, population as size, and continent as color.

Animated Chart

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

A play button and a slider appear under the chart. Viewers watch countries move across the years.

Other Handy Chart Types

  • px.histogram: shows the spread of one column.
  • px.box: compares groups with box plots.
  • px.pie: shows shares of a whole when categories stay few.
  • px.choropleth: colors a world or state map by values.
  • px.treemap: shows nested shares as rectangles.

Customize the Look

fig.update_layout(
    title="Income and Life Expectancy",
    xaxis_title="Income per person",
    yaxis_title="Years",
    template="plotly_white",
    legend_title="Continent")

Save and Share

fig.write_html("chart.html")
fig.write_image("chart.png")

The HTML file keeps every interactive feature, so anyone can open it in a browser. Writing an image file needs the kaleido package.

Design Tips

  • Give every chart a clear title and labeled axes.
  • Limit colors to a handful, and use accessible palettes.
  • Show helpful hover text, such as country names, instead of raw row numbers.
  • Avoid 3D effects that make values hard to compare.
  • Test the chart on a phone screen.

Example: Explaining a Chart to Teammates

A marketing team tracks weekly visits from three sources: search, email, and social media. A static line chart shows three lines, and readers squint at the values. A Plotly line chart lets each reader click the legend to hide two sources and study the third. Hovering reveals the exact visit count for any week. Teammates answer their own questions without asking the analyst for new charts. The analyst saves hours, and the team gains confidence in the numbers.

When Static Charts Still Win

Printed reports, slide decks with strict layouts, and academic papers need fixed images. Matplotlib and Seaborn handle those cases well. Choose Plotly when readers will explore the chart on a screen, and choose static charts when the chart must look identical everywhere.

Key Points

  • Plotly Express builds interactive charts in one line.
  • Hover, zoom, and animation help readers explore data themselves.
  • Charts export as standalone HTML for easy sharing.