Mathew K Analytics

Lesson 24 · Data visualisation in python

Introduction to Plotly: Creating Interactive Charts with Python

Start simple and add features slowly. Use colors and labels to guide your viewers. Save your best charts to share with friends or coworkers. The Plotly…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Tips for Using Plotly Effectively#

  • Start simple and add features slowly.
  • Use colors and labels to guide your viewers.
  • Save your best charts to share with friends or coworkers.

The Plotly documentation has plenty of examples if you get stuck.

Keep experimenting to discover new tricks! Each row shows the number of passengers for one month.

There are two columns: 'Month' and 'Passengers'.

Let us make a chart showing how these numbers change over time. import plotly.graph_objs as go import plotly.express as px import pandas as pd

Plotly is a powerful library for making beautiful and dynamic visualizations you can click, zoom, and explore.

By the end, you will know how to load data, build charts, and even share them with others.

Let us get started!

Data setup#

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv" df = pd.read_csv(url) print(df.shape) df.head()

Let us check what type our data columns are.#

print(df.dtypes)

Convert 'Month' to a datetime for better x axis handling.#

df['Month'] = pd.to_datetime(df['Month']) print(df['Month'].head())

A new line chart with proper dates#

fig = px.line(df, x='Month', y='Passengers', title='Monthly Airline Passengers (Datetime X)') fig.show()

Let us add a little style and color.#

fig = px.line(df, x='Month', y='Passengers', title='Monthly Airline Passengers', color_discrete_sequence=['green']) fig.update_traces(line=dict(width=3)) fig.show()

Add points to show each month clearly.#

fig = px.line(df, x='Month', y='Passengers', title='With Markers', markers=True) fig.show()

Highlight the biggest month using annotations.#

max_row = df[df['Passengers'] == df['Passengers'].max()] fig = px.line(df, x='Month', y='Passengers', title='Highlight Maximum')

Challenge: Try This Yourself!#

Make a chart that shows only the months where passenger numbers are below 200.

              Hint: Use pandas to filter `df['Passengers'] < 200` and make any Plotly chart you like.
              

Pause and see if you can do it on your own.

Share your results in the YouTube comments and let us know how it went! fig.show()

Let us try a bar chart for the same data.#

fig = px.bar(df, x='Month', y='Passengers', title='Monthly Passengers (Bar Chart)') fig.show()

Show only a part of the data (for example, five years).#

df_subset = df[(df['Month'] >= '1950-01-01') & (df['Month'] <= '1954-12-01')] fig = px.line(df_subset, x='Month', y='Passengers', title='First Five Years') fig.show()

Multiple lines: compare parts of the data.#

import numpy as np df['Year'] = df['Month'].dt.year yearly_avg = df.groupby('Year')['Passengers'].mean().reset_index() fig = px.line(yearly_avg, x='Year', y='Passengers', title='Average Passengers per Year') fig.show()

Add custom hover text to your chart.#

fig = px.line(df, x='Month', y='Passengers', title='Custom Hover Example', hover_data={'Month': True, 'Passengers': True}) fig.show()

Save your chart to an HTML file to share.#

fig = px.line(df, x='Month', y='Passengers', title='Save Chart Example') fig.write_html("my_chart.html")

Try making a chart from user input.#

user_title = input("What title do you want for your chart? ") fig = px.line(df, x='Month', y='Passengers', title=user_title) fig.show()

Quick mini-project: spot months above average.#

avg_passengers = df['Passengers'].mean() above_avg = df[df['Passengers'] > avg_passengers] print(f"Average passengers: {avg_passengers:.1f}") print("Months above average:") print(above_avg[['Month', 'Passengers']].head())

Chart those busy months in red.#

fig = px.scatter(above_avg, x='Month', y='Passengers', color_discrete_sequence=['red'], title='Months Above Average') fig.show()

If you get an error, check the error message.#

try: px.line(df, x='MYTH', y='Passengers')

Recap#

You have learned how to load data, make interactive charts, add style and features, and share your results.

Plotly helps you tell visual stories from data right inside your notebook.

Ready to keep going? Try more chart types or play with your own data!

Found this useful?

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