我正在绘制甘特图,使用巧妙的表达时间轴功能。我有问题的悬停文本渲染的日期字段。
plotly version: 4.5.4
这里给出的原始示例https://plotly.com/python/gantt/,Finish字段以正确的格式呈现为%Y-%m-%d
。
import plotly.express as px
import pandas as pd
df = pd.DataFrame([
dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex")
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource")
fig.update_yaxes(autorange="reversed")
fig.show()
我尝试使用以下代码自定义悬停文本字段。
import plotly.express as px
import pandas as pd
df = pd.DataFrame([
dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex")
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource"
, hover_data={"Start": True,
"Finish": True,
"Task": True,
"Resource": False}
)
fig.show()
现在,显示的Finish字段是以毫秒为单位的Start
和Finish
的差异。在上面的示例中,“Finish”值显示为5011200000。
我需要原始的Finish
值显示在悬停文本中。在这种情况下,2009-02-28
。
我只能通过在dataframe中创建Finish列的副本来解决这个问题,并将其用于悬停文本。
有什么方法可以不重复地正确呈现列吗?
发布于 2020-12-26 07:08:29
您可以使用hovertemplate
更改悬停工具提示中显示的值的格式,请参阅Plotly上的示例以及Plotly文档。
下面是一个基于代码的示例,其中的开始日期和结束日期都是%Y-%m-%d
格式的。请注意,x_start
和x_end
对应于PlolyT图字典中的base
和x
键。
import plotly.express as px
import pandas as pd
df = pd.DataFrame([
dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
dict(Task="Job B", Start='2009-03-01', Finish='2009-04-30', Resource="Anna")
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource")
fig.update_traces(hovertemplate="Start: %{base|%Y-%m-%d}<br>"
"End: %{x|%Y-%m-%d}<br>"
"Task: %{y}")
fig.show()
https://stackoverflow.com/questions/65457258
复制相似问题