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…
- CourseMastering Pandas
- Lesson50 of 44
- Video17 min
- FormatJupyter notebook · 12 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbBuilding 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))
First Visual: Explore Life Expectancy Trends#
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())
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}")
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())
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!")
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())
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.



