Let us explore how we can create the Timeline Plots with the Plotly Express module.
Plotly.express.timeline()
To create a Gantt chart in Plotly, we use the timeline() function. The function syntax and parameter list are as shown in the following:
The parameters are expressed as follows:
- data_frame – Specifies the data frame containing the columns used in the plot.
- x_start – Specifies the values used in the position marks along the x axis in the cartesian plane. You can specify these values as a column within the data_frame or a Pandas Series.
- x_end – Similar to x_start.
- y – Similar to x_start and x_end but the values in this parameter are used to position the marks along the y axis in the Cartesian plane.
- color – Specifies the value used assign a unique color to the marks of the plot.
- title – Sets a title for the plot.
- width/height – Sets the width and height of the figure in pixels.
The function creates a Gantt plot of the specified values as graph_objects.Figure type.
Basic Gantt Chart
Let us create a simple Gantt plot to illustrate how we can use the timeline() function.
df = [dict(
Task='Init', Start='2022-07-19', Finish='2022-07-30'),
dict(Task='Update ', Start='2022-08-01', Finish='2022-08-05'),
dict(Task='Production', Start='2022-08-06', Finish='2022-08-10')
]
fig = px.timeline(df, x_start='Start', x_end='Finish', y='Task')
fig.show()
The given code creates the Gantt figure of the provide data as shown in the following illustration:
Plotly Gantt Set the Discrete Color
You can set a discrete color for each bar by setting the color parameter. For example, to set a unique color for each project, we can run the following code:
df = [dict(
Task='Init', Start='2022-07-19', Finish='2022-07-30'),
dict(Task='Update ', Start='2022-08-01', Finish='2022-08-05'),
dict(Task='Production', Start='2022-08-06', Finish='2022-08-10')
]
fig = px.timeline(df, x_start='Start', x_end='Finish', y='Task', color='Task')
fig.show()
In this case, we set the color parameter to the Task column within the DataFrame.
This returns the following figure:
To create the title for the Gantt chart, we can use the title parameter as shown in the following code:
This sets the string as the title for the figure as shown in the following:
To add a text inside the bar plots, we can use the text parameter as shown in the following:
The resulting figure is as follows:
To set the width and height of the figure, you can use their respective parameters as shown in the following:
The resulting figure takes the specified dimensions despite the environment screen real estate.
Conclusion
In this article, we discussed how you can create a Gantt chart using the Plotly Express timeline() function.