Interactive Plots using Plotly Express (Part 1): Line Plot and 3D Scatter Plot Written by Kevin Jacobs

I'm Kevin, a Data Scientist, PhD student in NLP and Law and blog writer for Data Blogger.

This blog series is a beginners’ tutorial on how you can make interactive plots in a Jupyter notebook using Plotly Express. In this first blog post on this topic, we will go through the steps needed for creating a basic line Python plot and a 3D scatter plot.

Basic line plot

The most simple plot is a line plot which is the first plot that we will create. We will start by importing the required libraries for Plotly:

import pandas as pd
import numpy as np
import chart_studio.plotly as py
import seaborn as sns
import plotly.express as px
%matplotlib inline

init_notebook_mode(connected=True)
cf.go_offline()
The imports

Then, we can create a simple DataFrame based on random numbers (in a 25×3 matrix) and plot the results using Plotly:

df = pd.DataFrame(np.random.randn(25, 3), columns=['First', 'Second', 'Third'])
df.iplot()
Our first Plotly plot

And this is the result:

3D Scatter Plot

We can also create a scatter plot in 3 dimensions. That is not possible using only Matplotlib. For this scatter plot, we will download stock data and plot the year on the x-axis, the month on the y-axis and the change on the z-axis. As color, we will use the trade volume.

import yfinance as yf

df_aapl = df_aapl.assign(DateTime=pd.to_datetime(df_aapl.Date))
# Assign the year, month and weekday to the DataFrame
df_aapl = df_aapl.assign(year=df_aapl.DateTime.dt.year, month=df_aapl.DateTime.dt.month, weekday=df_aapl.DateTime.dt.weekday)
# Compute the percentage change
df_aapl = df_aapl.assign(change=df_aapl.Close.pct_change())
df_aapl.dropna()
# Remove outliers (with a change that is larger than 0.1)
df_aapl = df_aapl[df_aapl.change.apply(abs) < 0.1]
# Apply a log filter on the volume
df_aapl = df_aapl.assign(Volume=df_aapl.Volume.apply(np.log))

# Now we can create the 3D scatter plot!
fig = px.scatter_3d(df_aapl, x='year', y='month', z='change', color='Volume', size_max=1)
fig
3D scatter plot

This is the final result:

Here, you can see that the Apple stock (AAPL) was traded a lot around 2005, but less traded nowadays. If you have an interesting use case for 3D line plots or 3D scatter plots, please share it in the comments below.

Conclusion

This was part 1 of the “Interactive Plots using Plotly Express” series. If you have any suggestions for the next blog post, please let us know on Twitter.