We can implement python Gantt chart matplotlib using the broken_barh() function. We need to provide the X, Y-Axis dimensions as a parameter. In this article, We will implement a Gantt chart matplotlib chart stepwise with an explanation.
Python Gantt chart matplotlib Implementation –
Gantt charts are really important for visualizations. Here are the steps.
Step 1: Import Statement –
In this step, We will import the packages we need to draw the Gantt chart.
import matplotlib.pyplot as plt
Step 2: Creating subplot –
We need two subplots, One for the base. The second is specific to the Gantt chart.
fig, gnt = plt.subplots()
Step 3: Seting dimension –
In this step, We will define the dimensions for the base chart as well as the gantt chart. We will also set the visible labels on it.
gnt.set_ylim(0, 25) gnt.set_xlim(0, 50) gnt.set_xlabel('X-Axis') gnt.set_ylabel('Y-Axis') gnt.set_yticks([10, 15, 20]) gnt.set_yticklabels(['10', '15', '20'])
The first two statements (set_ylim and set_xlim) set the dimension of X-Axis and Y-Axis for the base chart. The third and fourth statement is (set_xlabel and set_ylabel) is just to print the labels. Now last two statements where we segment the Y-Axis and set the labels on it for more clarity.
We also need to turn on the grid line for more clarity of measurements of the matplotlib Gantt chart. We need to add the below line for that as well.
Step 4: Invoking the broken_barh() function for Gantt chart-
broken_barh chart accepts the below parameter for gantt chart.
1. xranges -sequence of tuples (xmin, xwidth)
Here is the important thing for us is xwidth. This is not xmax value. Hence the total length will be (xmin+ xwidth).
Here yheight is the same as xwidth.
3.facecolors defines the colors for the chart.
gnt.broken_barh([(15, 10)], (10, 5), facecolors =('tab:green')) gnt.broken_barh([(35, 10)], (1, 5), facecolors =('tab:pink'))
Complete code with Output –
Let’s merge the code from all the steps.
import matplotlib.pyplot as plt fig, gnt = plt.subplots() gnt.set_ylim(0, 25) gnt.set_xlim(0, 50) gnt.set_xlabel('X-Axis') gnt.set_ylabel('Y-Axis') gnt.set_yticks([10, 15, 20]) gnt.set_yticklabels(['10', '15', '20']) gnt.grid(True) gnt.broken_barh([(15, 10)], (10, 5), facecolors =('tab:green')) gnt.broken_barh([(35, 10)], (1, 5), facecolors =('tab:pink'))
Once we run the code we get the following chart.
I hope you have found this article informative. Please comment below in the comment box.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.