I am plotting Gannt chart using plotly express timeline function. I am having problems with the hover text rendering of the date field.
plotly version: 4.5.4
The original example given here https://plotly.com/python/gantt/ , the Finish field renders in the right format as %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()
I tried customizing the hover text fields using the below code.
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()
Now, the Finish field shown is the difference of Start
and Finish
in milliseconds. In the above example the 'Finish' value is shown as 5011200000 .
I need the original Finish
value to be shown in the hover text. In this case 2009-02-28
.
I could only solve this by creating a copy of Finish column in my dataframe and use that for the hover text.
Is there a way I get the correct rendering of the column without duplicating it?
You can change the format of the values shown in the hover tooltip using hovertemplate
, see this example on the Plotly website as well as the Plotly documentation .
I included an example below based on your code, where the start date and end date are both in %Y-%m-%d
format. Note that x_start
and x_end
correspond to the base
and x
keys in the Plotly figure dictionary.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.