Exercise
Using the Hang Seng Index dataset, create either a dropdown menu option or a set of buttons to alternate between the Close
and the Volume
series. Decide whether we should update
, relayout
, restyle
, etc.
Solution
-
An empty figure is created using the
go.Figure()
function on line 2. -
A scatter trace is added to the figure using the
fig.add_trace()
function on line 5. Thex
parameter is set toDate
to specify the x-axis data, and they
parameter is set toVolume
to specify the y-axis data. Thename
parameter is set toVolume
to specify the name of the trace for the legend. -
A list of dictionaries is created on line 8 with two items representing the buttons. The
label
parameter specifies the label of each button and themethod
andargs
parameters are used to specify the action to be taken when the button is clicked. In this case, the buttons switch the visibility of the trace betweenClose
andVolume
. -
The
update_layout()
function on line 14 is used to set the title of the figure to ‘HSI Data’ and add a dropdown menu with the buttons created in the previous step. Theupdatemenus
parameter is used to specify the dropdown menu with a list of dictionaries representing each button. Thedirection
parameter is set todown
to create a dropdown menu, thebuttons
parameter is set to the list of button dictionaries, and theshowactive
parameter is set toTrue
to highlight the currently active button. -
A dictionary
rangeslider
is created, on line 17 to customize the appearance of the range slider. Thebgcolor
parameter is used to set the background color of the slider, thebordercolor
parameter is used to set the color of the border, theborderwidth
parameter is used to set the width of the border, and thethickness
parameter is used to set the thickness of the slider. -
The
update_layout()
function on line 20 is used again to add the range slider to the x-axis. Thetitle
parameter specifies the title of the figure, and thexaxis
parameter is used to specify the range slider with therangeslider
dictionary.
Get hands-on with 1400+ tech skills courses.