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 with x and y values taken from the spy DataFrame.

  • A figure is created using the go.Figure() function on line 5 with data parameter set to a list containing the trace 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. The rangeslider_visible parameter is set to False to turn off the range slider, and the rangeselector parameter is used to specify a list of buttons with different time ranges. Each button is defined as a dictionary with a count parameter specifying the number of units in the range, a label parameter specifying the label of the button, and a step parameter specifying the unit of the range.

Get hands-on with 1400+ tech skills courses.