'How do I make a plotly timeline with int nr of months on the x-axis
I am trying to make a plotly timeline where the x_start and x_end arguments are such that the x-axis is an integer nr of months instead of a date format. I have tried to use integers or arrays with integers with no luck.
Example code that fails:
df1 = pd.DataFrame(data = {'Task':['T1.1'], 'Start':np.array((1,)), 'Finish':np.array((5,)), 'text':[""], 'WorkPackage':['WP1']})
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", text = "text", color = 'WorkPackage',width = None, height = None)
Solution 1:[1]
If you still need help with this, it looks like your question was answered here: Plotly Express timeline for Gantt Chart with integer xaxis?
Using what was suggested in the link, I made the following code and it worked.
# Import libraries
import pandas as pd
import plotly.express as px
# Create some data in a dictionary
mydict = {'Task': ['Task 1', 'Task 2', 'Task 3', 'Task 4'],
'Start': np.arange(1, 5),
'Finish': np.arange(6, 10)
}
# Make a DataFrame object from the dictionary
df = pd.DataFrame(mydict)
# Add a column for the delta
df['Delta'] = df['Finish'] - df['Start']
# Create Figure
fig = px.timeline(
df,
x_start='Start',
x_end='Finish',
y='Task',
color='Task',
)
# Update the layout
fig.layout.xaxis.type = 'linear'
# I found I needed to do this to get the tasks to show up as differnt colors
for i in np.arange(len(df)):
fig.data[i].x = df['Delta'].tolist()
# Show the figure
fig.show()
Solution 2:[2]
Thes answer from punjabWala81 does not work as intended when you are using a dict like this, where you have different deltas
mydict = {'Task': ['Task 1', 'Task 2', 'Task 3', 'Task 4'],
'Start': [ 1, 2, 3, 4],
'Finish': [10, 4, 7, 8]
}
Then you got this
which is not correct.
This is due to the fact, that we got this
To solve this issue we can do this for example
for i in np.arange(len(df)):
fig.data[i].x = (df['Delta'][i],)
print(fig.data[i].x)
see as well this post https://stackoverflow.com/a/71141457/7447940
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 |





