Exercise: Custom Buttons and Dropdown Menus

Practice with some lab exercises.

We'll cover the following

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. The x parameter is set to Date to specify the x-axis data, and the y parameter is set to Volume to specify the y-axis data. The name parameter is set to Volume 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 the method and args 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 between Close and Volume.

  • 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. The updatemenus parameter is used to specify the dropdown menu with a list of dictionaries representing each button. The direction parameter is set to down to create a dropdown menu, the buttons parameter is set to the list of button dictionaries, and the showactive parameter is set to True to highlight the currently active button.

  • A dictionary rangeslider is created, on line 17 to customize the appearance of the range slider. The bgcolor parameter is used to set the background color of the slider, the bordercolor parameter is used to set the color of the border, the borderwidth parameter is used to set the width of the border, and the thickness 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. The title parameter specifies the title of the figure, and the xaxis parameter is used to specify the range slider with the rangeslider dictionary.

Get hands-on with 1200+ tech skills courses.