完整程式碼:create_bar_chart_race_plots.py
概念驗證使用 plotly 呈現,動態長條圖可正常播放,但在更新畫布後,大小與標籤顯示的視覺效果不佳(如下方展示),因此最終改用其他方法製作成品。
early_collected = cumulative_votes_by_time_candidate[cumulative_votes_by_time_candidate['collected_at'] < pd.to_datetime('2024-01-13 17:30:00')]
max_cumulative_votes = early_collected['cumulative_sum_votes'].max()
fig = px.bar(early_collected,
x='cumulative_sum_votes',
y='candidate',
color='candidate',
animation_frame='collected_at', # 影片的時間軸。
animation_group='candidate', # 每個時間 y 軸顯示名稱。
range_x=[0, max_cumulative_votes], # x 軸最大最小值設定。
text='cumulative_sum_votes') # 顯示標籤值
fig.update_yaxes(categoryorder='total ascending') # 控制分類軸排序方式: total ascending → 按總值由大到小排序。
max_confirmed_votes = covid_19_confirmed['confirmed'].max()
fig = px.bar(covid_19_confirmed,
x='confirmed',
y='country',
color='country',
animation_frame='reported_on', # 影片的時間軸。
animation_group='country', # 每個時間 y 軸顯示名稱。
range_x=[0, max_confirmed_votes], # x 軸最大最小值設定。
text='confirmed') # 顯示標籤值
fig.update_yaxes(categoryorder ='total ascending') # 更新y軸:categoryorder 控制分類軸排序方式, total ascending → 按總值由大到小排序。
最終成品改以 raceplotly 製作。
vote_raceplot = barplot(early_collected,
item_column='candidate', # 指定類別變數。
value_column='cumulative_sum_votes',# 指定數值變數。
time_column='collected_at', # 指定日期時間變數。
top_entries=3) # 只顯示前 3 名 (預設為 10)。
fig = vote_raceplot.plot(item_label='Votes collected by candidate',
value_label='Cumulative votes',
frame_duration=50)# 每幀動畫停留的毫秒數。
confirmed_raceplot = barplot(covid_19_confirmed,
item_column='country', # 指定類別變數。
value_column='confirmed', # 指定數值變數。
time_column='reported_on') # 指定日期時間變數。
fig = confirmed_raceplot.plot(item_label='Confirmed by country',
value_label='Number of cases',
frame_duration=50) # 每幀動畫停留的毫秒數。