python plotly(px)动画帧日期顺序错误 [英] python plotly (px) animation frame date is in wrong order

查看:58
本文介绍了python plotly(px)动画帧日期顺序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用plotly express,我建立了类似于其

我的包括动画在内的条形图的代码如下.

  fig = px.bar(eu_vaccine_df,x ='国家/地区',y ='people_vaccinated_per_hundred',color =国家",animation_frame ='date_str',animation_group =国家",hover_name ='国家',range_y = [0,50],range_x = [0,30])fig.update_layout(template ='plotly_dark',保证金= dict(r = 10,t = 25,b = 40,l = 60))图show() 

最终结果中,动画帧上的日期是错误的.它首先显示了2021年的所有结果,然后显示了2020年的所有结果,如以下屏幕截图的底部所示.

解决方案

按日期排序我的df解决了该问题.

  covid_df ['date'] = pd.to_datetime(covid_df ['date'])covid_df = covid_df.sort_values('date',ascending = True)covid_df ['date'] = covid_df ['date'].dt.strftime('%m-%d-%Y') 

With plotly express I've built a bar chart similar to as shown on their website.

As px.bar did not allow me to run the animation frame on datetime64[ns] I transformed the datetime into a string as follows.

eu_vaccine_df['date_str'] = eu_vaccine_df['date'].apply(lambda x: str(x))
eu_vaccine_df[['date_str', 'date', 'country', 'people_vaccinated_per_hundred']].head()

The dataset on which I then run the px.bar looks as follows and contains 30 different countries.

The code for my barchart including animation looks as follows.

fig = px.bar(
  eu_vaccine_df,
  x='country', y='people_vaccinated_per_hundred',
  color='country',
  animation_frame='date_str',
  animation_group='country',
  hover_name='country',
  range_y=[0,50],
  range_x=[0,30]
)
fig.update_layout(
  template='plotly_dark',
  margin=dict(r=10, t=25, b=40, l=60)
)
fig.show()

In the end result the date on the animation frame is wrong. It first shows all results from 2021 and then all results from 2020 as shown at the bottom of the following screenshot.

解决方案

Sorting my df by the date solved the issue.

  covid_df['date'] = pd.to_datetime(covid_df['date'])
  covid_df = covid_df.sort_values('date', ascending=True)
  covid_df['date'] = covid_df['date'].dt.strftime('%m-%d-%Y')

这篇关于python plotly(px)动画帧日期顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆