Mathew K Analytics

Lesson 25 · Data visualisation in python

Creating Interactive Scatter, Line, and Bar Charts with Plotly in Python

Today, you will learn how to create beautiful, interactive scatter, line, and bar charts using the Plotly library. We will use real-world datasets, step by…

⬇ 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

Welcome to Interactive Charts in Python with Plotly!#

Today, you will learn how to create beautiful, interactive scatter, line, and bar charts using the Plotly library.

We will use real-world datasets, step by step. No previous coding or data experience is needed!

By the end, you will be able to create your own charts and explore data visually.

# Setup: import basic tools and filter warnings
import warnings; warnings.filterwarnings('ignore')
import pandas as pd
import plotly.express as px
 
 

Introduction to Plotly#

Plotly is a Python library for making interactive charts. You can zoom, pan, and hover over chart points to see more information.

Let us start with some sample data!

# Data setup: Load the Airline Passengers dataset from a CSV file
url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv'
df = pd.read_csv(url)
print('Shape:', df.shape)
df.head()
Shape: (144, 2)
Month Passengers
0 1949-01 112
1 1949-02 118
2 1949-03 132
3 1949-04 129
4 1949-05 121

Preview: What does our data look like?#

We have two columns: 'Month' and 'Passengers'. Now, let us turn this table into a simple visualization.

# Line chart: Number of passengers over time
fig = px.line(df, x='Month', y='Passengers', title='Airline Passengers Over Time')
fig.show()

Customizing Line Charts#

You can change the line color and style to make charts clearer or more fun. Let us try making the line red and adding markers for each data point.

fig = px.line(df, x='Month', y='Passengers',
              title='Airline Passengers - Custom Style',
              markers=True,
              line_shape='linear',
              color_discrete_sequence=['red'])
fig.show()

Scatter Plots: Seeing Patterns#

Scatter plots help spot relationships between two features. Let us make a scatter plot using the same dataset, treating each month as a point.

fig = px.scatter(df, x='Month', y='Passengers', title='Passengers Per Month - Scatter Plot')
fig.show()

Bar Charts: Comparing Values#

Bar charts are great for comparing values across different groups or periods. Let us look at the first ten months as a bar chart.

fig = px.bar(df.head(10), x='Month', y='Passengers', title='Passengers in First 10 Months')
fig.show()
# Adding labels and changing bar color
fig = px.bar(df.head(10), x='Month', y='Passengers',
            title='Colored Bars with Labels',
            color='Passengers',
            color_continuous_scale='Blues')
fig.update_traces(text=df.head(10)['Passengers'], textposition='outside')
fig.show()

Interactive Features of Plotly#

Every Plotly chart lets you zoom, pan, save, and get tips by hovering.

Try clicking the icons in the upper right of the chart to explore!

# What month do you want to look at?
month = input("Type a month in the format YYYY-MM (for example, 1950-06): ")
row = df[df['Month'] == month]
if not row.empty:
    print('Passengers in', month, ':', int(row['Passengers']))
else:
    print('Sorry, that month was not found!')
    
Passengers in 1950-06 : 149

Making Comparisons with Multiple Charts#

You can show more than one kind of chart at once to tell a fuller story. Let us put a line chart and a bar chart side by side.

# Show line and bar charts together with Plotly subplots
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=1, cols=2, subplot_titles=('Line Chart', 'Bar Chart'))
fig.add_trace(go.Scatter(x=df['Month'], y=df['Passengers'], name='Line', mode='lines+markers'), row=1, col=1)
fig.add_trace(go.Bar(x=df['Month'], y=df['Passengers'], name='Bar'), row=1, col=2)
fig.update_layout(title_text='Passengers: Two Chart Types')
fig.show()

Real-World Data: Your Turn#

We have used airline data so far. You can try with weather or health data, too! Swap out the dataset link, and see what changes in your charts.

# Try the Daily Minimum Temperatures dataset
weather_url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv'
weather_df = pd.read_csv(weather_url)
print('Shape:', weather_df.shape)
weather_df.head()
Shape: (3650, 2)
Date Temp
0 1981-01-01 20.7
1 1981-01-02 17.9
2 1981-01-03 18.8
3 1981-01-04 14.6
4 1981-01-05 15.8
# Plot temperatures over time
fig = px.line(weather_df, x='Date', y='Temp', title='Daily Minimum Temperatures')
fig.show()
# Mini-project: Compare summer and winter averages
weather_df['Date'] = pd.to_datetime(weather_df['Date'])
weather_df['Month'] = weather_df['Date'].dt.month
summer_temp = weather_df[weather_df['Month'].isin([12, 1, 2])]['Temp'].mean()
winter_temp = weather_df[weather_df['Month'].isin([6, 7, 8])]['Temp'].mean()
fig = px.bar(x=['Summer (Dec-Jan-Feb)', 'Winter (Jun-Jul-Aug)'], y=[summer_temp, winter_temp],
            labels={'x':'Season', 'y':'Average Min Temp'}, title='Average Temperatures by Season')
fig.show()
# Best practice: Save your favorite chart as an image file
fig = px.line(df, x='Month', y='Passengers', title='Line Chart Example')
fig.write_image('passengers_chart.png')
print('Chart saved as passengers_chart.png!')
Chart saved as passengers_chart.png!
# Troubleshooting: What if you see the chart area but no chart?
print('If your chart did not show up, check:')
print('- Did you use fig.show()?')
print('- Is the column name spelled correctly?')
print('- Did the dataset load without errors?')
If your chart did not show up, check:
- Did you use fig.show()?
- Is the column name spelled correctly?
- Did the dataset load without errors?
# Tip: Add chart titles and axis labels for clarity
fig = px.bar(df.head(5), x='Month', y='Passengers', title='Chart with Custom Labels', labels={'Month': 'Year-Month', 'Passengers': 'Total People'})
fig.show()

Challenge: Make Your Own Chart#

Try making a new chart from one of the datasets. Play with colors, chart types, and labels.

What will you visualize next?

Recap: What You Learned#

  • How to load real data in Python.
  • How to make line, scatter, and bar charts with Plotly.
  • How to make your charts interactive and personal.
  • How to save and share your work.

Great job exploring data like a pro!

Want More?#

Try other datasets, chart types, or ideas.

Subscribe for more Python and data science lessons on YouTube!

Found this useful?

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