Exercise: Data Buttons on Line Charts
Practice with some lab exercises.
We'll cover the following...
Exercise 1
Create a red line chart of the spy closing prices. Add date buttons for 20 years into the past, 10 years into the past, 5 years into the past, 1 year into the past, 6 months into the past, 3 months into the past, 1 month into the past, the year so far and the month so far. Also, add an option to see all of the available data.
Solution
-
A trace is created using the
go.Scatter()
function on line 2 withx
andy
values taken from thespy
DataFrame. -
A figure is created using the
go.Figure()
function on line 5 withdata
parameter set to a list containing thetrace
object. -
The
update_xaxes()
function on line 8 is used to customize the x-axis of the figure by turning off the range slider and adding a range selector with a set of predefined date ranges. Therangeslider_visible
parameter is set toFalse
to turn off the range slider, and therangeselector
parameter is used to specify a list of buttons with different time ranges. Each button is defined as a dictionary with acount
parameter specifying the number of units in the range, alabel
parameter specifying the label of the button, and astep
parameter specifying the unit of the range.