我已经使用plotly成功创建了一个动画散点图,现在我想用自定义文本替换动画每一帧中的标题。
我参考了此聊天中的解决方案以尝试实现此目的: https://community.plotly.com/t/dynamic-animation-title-annotation/38747/3
输入数据为:
print(titles.to_dict())
{'年份': {0: 2021, 1: 2022, 2: 2023}, '文本': {0: '标题 1', 1: '标题 2', 2: '标题 3'}}
print(tagged_df.to_dict())
{'未命名:0': {0: 1266, 1: 1289, 2: 1293, 3: 1304, 4: 1305, 5: 1311, 6: 1776, 7: 1790, 8: 1799}, '位置': {0: '澳大利亚', 1: '澳大利亚', 2: '比利时', 3: '比利时', 4: '澳大利亚', 5: '澳大利亚', 6: '比利时', 7: '澳大利亚', 8 : '澳大利亚'}, '时间': {0: 2021, 1: 2021, 2: 2021, 3: 2022, 4: 2022, 5: 2022, 6: 2023, 7: 2023, 8: 2023}, 'Value_rates ':{0:0.02833333,1:-0.5487667,2:-0.5487667,3:0.3415667,4:1.636667,5:0.3415667,6:1.350987085,7:1.350987085,8: 3.580073801},'Value_cpi':{0:2.86391 , 1: 2.766667, 2: 2.440248, 3: 9.597511, 4: 6.594097, 5: 8.54687, 6: 2.345248207, 7: 2.382125997, 8: -100.0}, '区域': {0: 'DM_其他', 1: 'DM_Europe ', 2: 'DM_Europe', 3: 'DM_Europe', 4: 'DM_Other', 5: 'DM_Europe', 6: 'DM_Europe', 7: 'DM_Europe', 8: 'DM_Other'}, 'COUNTRY_NAME': { 0: '澳大利亚', 1: '奥地利', 2: '比利时', 3: '比利时', 4: '澳大利亚', 5: '奥地利', 6: '比利时', 7: '奥地利', 8: '澳大利亚'}, 'COLOUR_tag': {0: '紫色', 1: '粉色', 2: '粉色', 3: '粉色', 4: '紫色', 5: '粉色', 6: '粉色' ', 7: '粉色', 8: '紫色'}, 'SIZE_tag': {0: 50, 1: 50, 2: 50, 3: 50, 4: 50, 5: 50, 6: 50, 7: 50, 8: 50}}
我的代码如下。 图表看起来不错,但标题并未针对每一帧进行更新。我该如何解决这个问题?
#Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
# Create the scatter plot
fig = px.scatter(tagged_df, x="Value_cpi", y="Value_rates",
animation_frame="TIME",
animation_group="LOCATION",
color="COLOUR_tag",
hover_name="COUNTRY_NAME",
size=tagged_df['SIZE_tag'].astype(float), # Convert SIZE_tag to numeric
log_x=False,
range_x=[-5, 90], range_y=[-5, 50],
title='This Title needs to be replaced',
labels={'Value_cpi': 'Inflation Rate', 'Value_rates': 'Nominal Interest Rate (3m T-Bill)'},
width=960, height=540,
template='plotly_dark',
size_max=50, # Set the maximum dot size
)
# Iterate through the buttons to set 'redraw': True
for button in fig.layout.updatemenus[0].buttons:
button['args'][1]['frame']['redraw'] = True
# Update titles for each animation frame
for k in range(len(fig.frames)):
matching_rows = tagged_df[tagged_df["TIME"].astype(int) == int(fig.frames[k].name)]
if not matching_rows.empty:
chart_title = titles[titles['Year'] == int(fig.frames[k].name)]['Text'].values[0]
fig.frames[k]['layout'].update(title_text=chart_title)
fig.update_traces(
marker=dict(opacity=0.7),
selector=dict(mode='markers') # Ensure only markers are affected by the update
)
fig.show()
我认为代码的这部分
titles[titles['Year'] == int(fig.frames[k].name)]['Text'].values[0]
为每个帧返回相同的值,因此图表标题没有改变。如果您想更改一年中每一帧的标题,您可以这样做:
# Update titles for each animation frame
for k in range(len(fig.frames)):
matching_rows = tagged_df[tagged_df["TIME"].astype(int) == int(fig.frames[k].name)]
if not matching_rows.empty:
custom_title = matching_rows['TIME'].values[0]
fig.frames[k]['layout'].update(title_text='Year :'+str(custom_title))