Date Buttons on Line Charts

Learn to enhance the line charts by adding date buttons, allowing us to efficiently filter data for frequently used time periods and gain valuable insights.

We'll cover the following...

Our data

For this lesson, let’s use some data on the stock price of Alibaba. We can print out the top few rows to see what it looks like below:

Press + to interact
# Import libraries
import pandas as pd
import numpy as np
# Import datasets
alibaba = pd.read_csv('/usr/local/csvfiles//alibaba.csv', parse_dates=['Date'])
print(alibaba.head())

Let’s plot all of the data to ascertain the patterns in the data:

Press + to interact
# Import libraries
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Import dataset
alibaba = pd.read_csv('/usr/local/csvfiles//alibaba.csv', parse_dates=['Date'])
# Make traces and add
trace1 = go.Scatter(x=alibaba['Date'],
y=alibaba['Open'],
marker=dict(color='#7F00FF'),
name='Opening Price',
mode='lines')
trace2 = go.Scatter(x=alibaba['Date'],
y=alibaba['Close'],
marker=dict(color='black'),
name='Closing Price',
mode='lines')
fig = go.Figure(data=[trace1, trace2])
# Format and show
fig.update_layout(title=go.layout.Title(text='Alibaba Stock prices', x=0.5, xref='paper'))
fig.show()

Now we could use pandas and filter the data so that we only get the range we are interested in, but it turns out that we can filter by date effortlessly using Plotly functionality. This introduces us to the next important point which ...