I am building an animated map using Plotly Express
px.choropleth_mapbox. I use it to generate one PNG file per day (via
fig.write_image()) and then I stitch them together to have an animation. That part works just fine.
I want to display the date of each day in a changing position that I calculate based on the date. Basically I calculate the timeframe of all dates in seconds and then divide the difference of the current date to the first date by that value.
It looks like this (the
date column is of type
# Get min and max dates of the whole dataset first_date = df['date'].min() last_date = df['date'].max() # Get all unique dates and sort them dates = df['date'].unique() dates.sort() # Loop through the dates for date in dates: # Convert to Pandas datetime date = pd.to_datetime(date) # Create a new dataframe containing just the rows for the current date df_plot = df[df['date'] == date] # Calculate position of the date total_seconds = (last_date - first_date).total_seconds() now_seconds = (date - first_date).total_seconds() date_position = 1 - (now_seconds / total_seconds) # Start plotting fig = px.choropleth_mapbox( df_plot, ... ) # Show current date in the calculated position fig.update_layout( annotations=[ dict( xref='paper', yref='paper', x=1, y=date_position, showarrow=False, text='<b>' + str(date.strftime('%d.%m.%Y')) + '</b>', ), ] )
The original code has much more configurations, but I stripped it down to the necessary items.
This basically works: The date is shown on the upper right side for the first day and then slides down with each following day. But now the strange thing happens: On some days (for example, 19 Nov 2020) the date jumps up a little bit (not very much, but enough to note it clearly).
I guessed there was some error in my calculation. But when I plot the calculated values, they form a straight line with no visible error. Also
.describe looks just fine: All calculated values have the same difference to the next and the last one, mean, std etc all make sense and indicate a linear decline of the values.
I also tried calculating the position differently, not using the date value but rather the position of the date in the timeframe, like so:
# Set count to zero num = 0 # Get total number of unique dates num_total = len(df['date'].unique()) # Loop through the dates for date in dates: ... # Calculate position of the date date_position = 1 - (num / num_total) # Increase the count by 1 num += 1 # Start plotting fig = px.choropleth_mapbox( df_plot, ... )
But the result is the same. I even had the calculated value displayed next to the date in the plot and while the values declined, the date still jumped up.
Am I missing something regarding the positioning of annotations? I would be thankful for any hint.