Time buttons
1. Time buttons
Let's learn how to create time buttons in Plotly with Python.2. What are time buttons?
Time buttons can be added to line charts to filter or zoom in on a specific time slice. You can see common time buttons on most stock websites, like this from Yahoo Finance. For example, 1D shows data for the last day, 1M for the previous month, 1Y for the last year, and YTD shows the year-to-date.3. Time buttons in Plotly
In Plotly, each time button is a dictionary with a few key elements The label is just the text that appears on the button, count is how many steps to take when clicking the button, and step is what date period to move such as year, month, day and more. stepmode is a bit more complex. It can either be 'backward' or 'todate'. 'backward' moves straight back by the number of units specified in the count. 'todate' moves backward by count, but then snaps to the start of the next full time period. Let's walk through an example to clarify this.4. 'backward' vs. 'todate'
Say our dataset ends on October 20th, and we use a 6-month button with count=6 and step='month'. With stepmode="backward", the plot starts at April 20th - exactly 6 months back. With stepmode="todate", it snaps to May 1st - the beginning of the month following the cutoff date.5. Sydney rainfall example
Let's chart the rainfall from a weather station in Sydney in 2020. Firstly, let's create the buttons. Buttons are specified as a list of dictionaries. We create a list of two buttons. The first we want to have is six-months-to-date so we set count as 6, the step as month and the stepmode as todate with an appropriate label. The second is a two-week-to-date button. Since there's no 'week' step, we set count=14 and step='day'.6. Adding the time buttons
Now, let's create the chart and add the buttons. For simplicity, let's use Plotly Express to create a line chart, setting the appropriate arguments. To add the buttons, we set the buttons argument which is part of the rangeselector argument inside the xaxis dictionary, which is passed to our generic update_layout function. We can see our plot now has buttons. But what do they do?7. Clicking our time buttons
Clicking the 2-week-to-date button zooms the plot to begin on October 17th, 14 days before the last date in the data. Clicking the 6-month-to-date button zooms the plot to begin on May 1st, which is 6 months before the last date in the data. Clicking the buttons again will reset the plot.8. Let's practice!
Let's practice adding time buttons to our visualizations.Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.