Time buttons

Introduction to Data Visualization with Plotly in Python

Alex Scriven

Data Scientist

What are time buttons?

 

Time buttons allow filter/zoom in line charts.

Often seen on most stock websites such as Yahoo Finance (TESLA stock);

  • 1D = Show data for the last day, 1M = for the last month, 1Y = for the last year, etc.
  • YTD = Show data for the 'year to date'

 

Yahoo finance buttons

Introduction to Data Visualization with Plotly in Python

Time buttons in Plotly

 

Time buttons in Plotly are a dictionary specifying:

  • label = Text to appear on the button
  • count = How many steps to take when clicking the button
  • step = What date period to move ('month', 'year', 'day', etc.)
  • stepmode = Either 'todate' or 'backward'
    • 'todate' = From the beginning of the nearest whole time period denoted in step (after going backwards by count)
    • 'backward' = Just go backwards by count
Introduction to Data Visualization with Plotly in Python

'todate' vs. 'backward'

 

To illustrate todate vs. backward, consider a dataset finishing on October 20th and a 6-month button (count=6, step='month') with each option.

 

  • stepmode='backward' would zoom the plot to start on April 20th (6 months backward)
  • stepmode='todate' would zoom the plot to start on May 1st (start of the nearest month to April 20th)
Introduction to Data Visualization with Plotly in Python

Sydney rainfall example

 

Let's chart the rainfall from a weather station in Sydney in 2020.

Create the buttons

  • Buttons are specified as a list of dictionaries
date_buttons = [
{'count': 6, 'step': "month", 'stepmode': "todate", 'label': "6MTD"},

{'count': 14, 'step': "day", 'stepmode': "todate", 'label': "2WTD"} ]
Introduction to Data Visualization with Plotly in Python

Adding the time buttons

Now let's create the chart and add them;

fig = px.line(data_frame=rain, x='Date', 
        y='Rainfall', 
        title="Rainfall (mm) in Sydney")

fig.update_layout( {'xaxis': {'rangeselector': {'buttons': date_buttons} }}) fig.show()

Our line chart has the buttons:

line chart with buttons

Introduction to Data Visualization with Plotly in Python

Clicking our time buttons

 

Clicking the 2WTD button:

Rain last fortnight

 

Clicking the 6MTD button:

Rain last 6 months

Introduction to Data Visualization with Plotly in Python

Let's practice!

Introduction to Data Visualization with Plotly in Python

Preparing Video For Download...