Mathew K Analytics

Lesson 50 · Mastering Pandas

Turn Raw Data into Interactive Charts (Plotly + Pandas)

Welcome! Today we will unlock the power of plotly and pandas by creating interactive visualizations from real-world data. We will start from loading a…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Building Interactive Visuals with Plotly and Pandas#

Welcome! Today we will unlock the power of plotly and pandas by creating interactive visualizations from real-world data.

We will start from loading a dataset, explore it, and build step-by-step up to rich interactive charts you can adapt for your own projects.

Let us dive in!

import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings("ignore")
# Suppress any warnings for a cleaner experience.

Loading A Real-World DataFrame#

We will use the classic Gapminder dataset, which tracks global life expectancy, GDP, and population over time.

This is great for learning how to plot time trends and compare countries interactively.

# Data setup (Gapminder Dataset)
import plotly.express as px
df = px.data.gapminder()
print(df.shape)
print(df.head(3))
(1704, 8)
       country continent  year  lifeExp       pop   gdpPercap iso_alpha  \
0  Afghanistan      Asia  1952   28.801   8425333  779.445314       AFG   
1  Afghanistan      Asia  1957   30.332   9240934  820.853030       AFG   
2  Afghanistan      Asia  1962   31.997  10267083  853.100710       AFG   

   iso_num  
0        4  
1        4  
2        4  

Let us make a simple line plot to see how life expectancy has changed for a single country over time.

Plotly makes this just a few lines of code.

country = 'Japan'
df_japan = df[df['country'] == country]

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=df_japan['year'], y=df_japan['lifeExp'], mode='lines+markers', name='Life Expectancy'))
fig.update_layout(title=f'Life Expectancy Trends in {country}', xaxis_title='Year', yaxis_title='Life Expectancy')
fig.show()

Quick Data Exploration#

Let us review what columns we have and find any missing data.

This is always useful before plotting new visuals.

print(df.columns)
print('\nMissing values by column:')
print(df.isna().sum())
Index(['country', 'continent', 'year', 'lifeExp', 'pop', 'gdpPercap',
       'iso_alpha', 'iso_num'],
      dtype='object')

Missing values by column:
country      0
continent    0
year         0
lifeExp      0
pop          0
gdpPercap    0
iso_alpha    0
iso_num      0
dtype: int64

Aggregating for Comparison#

Let us look at average life expectancy for several Asian countries on the latest available year.

This is a powerful way to compare across many countries together.

latest_year = df['year'].max()
asian_countries = ['China', 'India', 'Japan', 'South Korea', 'Singapore', 'Thailand', 'Vietnam']
df_asia = df[(df['country'].isin(asian_countries)) & (df['year'] == latest_year)]

fig = px.bar(df_asia, x='country', y='lifeExp', color='country', title='Average Life Expectancy in Asia (2007)')
fig.show()

Interactive Scatter Plot: GDP vs. Life Expectancy#

Scatter plots are great for showing relationships.

We will make an interactive bubble plot comparing GDP per Capita with Life Expectancy, using bubble size for population.

fig = px.scatter(df[df['year'] == latest_year],
                 x='gdpPercap', y='lifeExp', size='pop', color='continent',
                 hover_name='country', log_x=True, size_max=60,
                 title='GDP vs. Life Expectancy (2007): Bubble = Population')
fig.show()

Mini Interactive Challenge!#

Switch to your favorite continent. Find the country with the highest GDP per Capita in that region for the latest year.

Hint: Use DataFrame filtering and .sort_values().

# Try it: Find top GDP per Capita for a selected continent
continent = input("Choose a continent (Asia, Europe, Africa, Americas, Oceania): ")
df_region = df[(df['continent'] == continent) & (df['year'] == latest_year)]
top_country = df_region.sort_values(by='gdpPercap', ascending=False).iloc[0]
print(f"Country: {top_country['country']}, GDP per Capita: {top_country['gdpPercap']:.2f}")
Country: Norway, GDP per Capita: 49357.19

Make An Animated Visual!#

Plotly supports powerful animated visualizations that tell stories over time.

Let us make an animated bubble chart showing development across the decades.

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=60,
                 range_x=[100,100000], range_y=[20,90],
                 title='Animated GDP vs. Life Expectancy Over Time')
fig.show()

Creating a Pivot Table in Pandas#

Sometimes, we want to summarize or reshape data before plotting.

Let us build a pivot table to see average life expectancy for each continent and year.

pivot = df.pivot_table(values='lifeExp', index='year', columns='continent', aggfunc='mean')
print(pivot.head())
continent     Africa  Americas       Asia     Europe  Oceania
year                                                         
1952       39.135500  53.27984  46.314394  64.408500   69.255
1957       41.266346  55.96028  49.318544  66.703067   70.295
1962       43.319442  58.39876  51.563223  68.539233   71.085
1967       45.334538  60.41092  54.663640  69.737600   71.310
1972       47.450942  62.39492  57.319269  70.775033   71.910

Time-Series Multi-Line Chart#

We can now plot how continents' life expectancy changes over time on the same chart.

This style reveals broad trends and makes comparisons simple.

fig = go.Figure()
for continent in pivot.columns:
    fig.add_trace(go.Scatter(x=pivot.index, y=pivot[continent], mode='lines+markers', name=continent))
fig.update_layout(title='Average Life Expectancy by Continent', xaxis_title='Year', yaxis_title='Life Expectancy')
fig.show()

Exporting and Sharing Visuals#

Pandas with Plotly can save visuals as images or HTML, perfect for presentations or sharing online.

Let us export our last chart as an HTML file.

fig.write_html('life_expectancy_by_continent.html')
print("Chart saved as 'life_expectancy_by_continent.html'. Open it in your browser!")
Chart saved as 'life_expectancy_by_continent.html'. Open it in your browser!

Debugging: Common Plotly/Pandas Issues#

If your plot does not look right, check for data types, missing values, and column names.

Most chart errors come from small typos or unexpected nulls. Read error messages for clues!

# Quick check for column names and types
print(df.dtypes)
# Check for obvious data issues
print(df.isnull().sum())
country       object
continent     object
year           int64
lifeExp      float64
pop            int64
gdpPercap    float64
iso_alpha     object
iso_num        int64
dtype: object
country      0
continent    0
year         0
lifeExp      0
pop          0
gdpPercap    0
iso_alpha    0
iso_num      0
dtype: int64

Recap and Next Steps#

You now know how to:

  • Import real-world data
  • Explore, filter, and aggregate data with pandas
  • Create static and animated interactive visuals with Plotly
  • Export and share your insights

Keep practicing by applying these steps to other datasets!

Found this helpful? Ask your questions below and try one new chart idea this week.#

If you enjoyed this lesson, subscribe for more deep dives into pandas and data science tools!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.