How to Make a Gantt Chart in Matplotlib

Draw a Gantt chart in Matplotlib with ax.barh, using each task's start date as left= and its duration as the bar width, then add progress, a today line, milestones, dependency arrows, and broken_barh rows.

Matplotlib has no Gantt function, but ax.barh() makes one in a single call: pass the task names, each task's duration as the bar width, and its start date as left=. Pandas dates and timedeltas work directly, so ax.barh(df["task"], df["end"] - df["start"], left=df["start"]) is the whole chart. Then ax.invert_yaxis() puts the first task at the top.

Quick Example

This is a ten-task kitchen renovation, with each bar colored by the trade doing the work.

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patches import Patch

df = pd.DataFrame(
    [
        ("Permits", "Contractor", "2026-03-02", 12),
        ("Demolition", "Contractor", "2026-03-16", 5),
        ("Plumbing rough-in", "Plumber", "2026-03-23", 5),
        ("Electrical rough-in", "Electrician", "2026-03-23", 8),
        ("Drywall", "Contractor", "2026-03-31", 10),
        ("Painting", "Painter", "2026-04-13", 5),
        ("Cabinets", "Carpenter", "2026-04-20", 8),
        ("Countertops", "Carpenter", "2026-04-28", 9),
        ("Plumbing finish", "Plumber", "2026-05-11", 3),
        ("Electrical finish", "Electrician", "2026-05-11", 4),
    ],
    columns=["task", "trade", "start", "days"],
)
df["start"] = pd.to_datetime(df["start"])
df["end"] = df["start"] + pd.to_timedelta(df["days"], unit="D")

colors = {"Contractor": "#5f5a73", "Plumber": "#1d7fb8", "Electrician": "#f2a541",
          "Painter": "#5c946e", "Carpenter": "#a4243b"}

fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.barh(df["task"], df["end"] - df["start"], left=df["start"],
        color=df["trade"].map(colors), height=0.6)
ax.invert_yaxis()
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
ax.grid(axis="x", alpha=0.3)
ax.set_axisbelow(True)
ax.legend(handles=[Patch(color=c, label=t) for t, c in colors.items()],
          loc="lower left", title="Trade")
ax.set_title("Kitchen renovation schedule", loc="left")
plt.show()

Matplotlib Gantt chart of a kitchen renovation: ten horizontal bars from Permits at the top in early March to Plumbing finish and Electrical finish at the bottom in mid May, colored by trade, with Monday dates on the x-axis

The project runs from March 2 to May 15, 2026. Plumbing and electrical rough-in overlap in the week of March 23, and so do the two finish tasks at the end.

How the Gantt chart is built

A Gantt bar is a horizontal bar that doesn't start at zero. barh already supports that:

Argument Gantt meaning
y (first argument) Task names, one row each. Strings become categories in the order given
width (second argument) Duration: end - start, a pandas timedelta Series
left= Start date of each bar
color= One color per bar. df["trade"].map(colors) looks each task's trade up in the dict
height= Bar thickness as a fraction of the row, 0.8 by default

A few details matter:

  • ax.invert_yaxis(): barh draws the first row at the bottom. Inverting the axis puts the first task at the top, which is how schedules are read.
  • Durations as end dates: the data stores a start date and a number of calendar days, and end = start + days. A 5-day task that starts on a Monday ends at midnight on Saturday, so its bar covers Monday through Friday. If your data already has an end date for the last working day, add one day before plotting or the bar comes up a day short.
  • Date ticks: mdates.WeekdayLocator(byweekday=mdates.MO) puts a tick on every Monday and DateFormatter("%b %d") labels it "Mar 02". The custom date formatting post covers the other locators and formatters.
  • The legend: the bars have no labels, so the legend is built from Patch handles, one per trade. Passing label= to barh would label the whole bar container, not each color.

Show percent complete and today's date

For a status report, draw each bar twice: a pale full-length bar for the plan, and a solid bar on top for the part that's done. ax.axvline marks today.

df["done"] = [1, 1, 1, 1, 1, 0.6, 0, 0, 0, 0]
today = pd.Timestamp("2026-04-16")
duration = df["end"] - df["start"]
trade_colors = df["trade"].map(colors)

fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.barh(df["task"], duration, left=df["start"], color=trade_colors, alpha=0.3, height=0.6)
done = ax.barh(df["task"], duration * df["done"], left=df["start"],
               color=trade_colors, height=0.6)
ax.bar_label(done, labels=[f"{p:.0%}" if p > 0 else "" for p in df["done"]],
             padding=4, fontsize=9)
ax.axvline(today, color="#c0392b", linewidth=1.5)
ax.text(today, -0.9, " Today", color="#c0392b", va="bottom", fontsize=10)
ax.invert_yaxis()
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
ax.grid(axis="x", alpha=0.3)
ax.set_axisbelow(True)
ax.set_title("Kitchen renovation: status on April 16", loc="left")
plt.show()

Gantt chart with pale planned bars and solid completed portions: the first five tasks are 100 percent done, Painting is 60 percent done, and a red vertical Today line on April 16 crosses the Painting bar

duration * df["done"] scales each timedelta by its fraction, so the solid bar stops partway along the pale one. ax.bar_label writes the percentage at the end of the solid bar, with an empty label for tasks that haven't started. See the bar_label post for more label formats.

The "Today" text sits at y=-0.9, just above the first row: with category labels, row i is at y=i, and after invert_yaxis() smaller numbers are higher up.

Add milestones and dependency arrows

A milestone is a single date, so draw it as a marker instead of a bar. Dependencies (task B can't start until task A ends) are arrows from the end of one bar to the start of the next, drawn with ax.annotate.

milestones = {"Permit approved": "2026-03-14", "Final inspection": "2026-05-15"}
depends_on = [("Demolition", "Plumbing rough-in"), ("Demolition", "Electrical rough-in"),
              ("Electrical rough-in", "Drywall"), ("Drywall", "Painting"),
              ("Painting", "Cabinets"), ("Cabinets", "Countertops"),
              ("Countertops", "Plumbing finish"), ("Countertops", "Electrical finish")]
row = {task: i for i, task in enumerate(df["task"])}
row |= {name: len(df) + i for i, name in enumerate(milestones)}

fig, ax = plt.subplots(figsize=(9, 5), layout="constrained")
ax.barh(df["task"], df["end"] - df["start"], left=df["start"],
        color=df["trade"].map(colors), height=0.5)
for name, date in milestones.items():
    ax.scatter(pd.Timestamp(date), name, marker="D", s=80, color="#222222", zorder=3)

ends = df.set_index("task")["end"]
starts = df.set_index("task")["start"]
for before, after in depends_on:
    ax.annotate("", xy=(starts[after], row[after]), xytext=(ends[before], row[before]),
                arrowprops=dict(arrowstyle="-|>", color="#555555", lw=1,
                                shrinkA=0, shrinkB=2,
                                connectionstyle="angle,angleA=0,angleB=90,rad=0"))

for saturday in pd.date_range("2026-02-28", "2026-05-16", freq="W-SAT"):
    ax.axvspan(saturday, saturday + pd.Timedelta(days=2), color="#000000", alpha=0.05, lw=0,
               zorder=0)

ax.invert_yaxis()
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
ax.set_xlim(pd.Timestamp("2026-02-28"), pd.Timestamp("2026-05-18"))
ax.set_title("Task dependencies and milestones (weekends shaded)", loc="left")
plt.show()

Gantt chart with right-angle arrows from the end of each task to the start of the task that depends on it, black diamond milestones for Permit approved on March 14 and Final inspection on May 15 in their own rows, and light gray weekend stripes

How it works:

  • Milestone rows: ax.scatter(date, name) with a string y value adds a new category row after the task rows, so the two diamonds get labeled rows of their own at the bottom.
  • Arrow positions: annotate needs numeric y values for the rows, which is what the row dict holds. connectionstyle="angle,angleA=0,angleB=90" makes the arrow leave the bar horizontally and drop vertically into the next task, the usual Gantt look. The arrows post covers the other arrow and connection styles.
  • Weekends: pd.date_range(..., freq="W-SAT") gives every Saturday, and axvspan shades it and the Sunday after. zorder=0 keeps the stripes behind the bars. With the shading on, five tasks run through a weekend: Permits, Electrical rough-in, Drywall, Cabinets, and Countertops. If the crews don't work weekends, those durations are too short; the tips below show how to count business days instead.

Tasks with gaps: broken_barh

Some rows have more than one bar: a trade that comes back for a second visit, or a machine booked in several slots. ax.broken_barh(xranges, yrange) draws any number of bars in one row. Here each row is a trade, showing the days it's on site.

trades = list(colors)

fig, ax = plt.subplots(figsize=(9, 3.2), layout="constrained")
for i, trade in enumerate(trades):
    visits = df[df["trade"] == trade]
    xranges = list(zip(visits["start"], visits["end"] - visits["start"]))
    ax.broken_barh(xranges, (i, 0.6), align="center", color=colors[trade])
ax.set_yticks(range(len(trades)), trades)
ax.invert_yaxis()
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
ax.grid(axis="x", alpha=0.3)
ax.set_axisbelow(True)
ax.set_title("When each trade is on site", loc="left")
plt.show()

Five-row chart drawn with broken_barh, one row per trade: the Contractor row has three bars for Permits, Demolition, and Drywall, the Plumber and Electrician rows each have a rough-in bar in late March and a finish bar in May, and the Carpenter row has one continuous bar from April 20 through May 6

xranges is a list of (start, width) pairs, and dates with timedelta widths work just like in barh. yrange is (y, height). align="center" centers the bar on y, so it lines up with the tick from set_yticks. That argument is new in Matplotlib 3.11; on older versions leave it out and pass (i - 0.3, 0.6) instead, since the bar always starts at the bottom of the range.

The plumber and electrician are each on site twice, about six weeks apart, while the carpenter's cabinets and countertops run back to back.

Matplotlib or Plotly for a Gantt chart?

Plotly has a dedicated function, px.timeline(), covered in the Plotly Gantt chart post.

Matplotlib barh Plotly px.timeline
Output Static PNG, SVG, or PDF Interactive HTML (hover, zoom), PNG with Kaleido
Setup Compute end - start, pass left= Pass x_start= and x_end= column names
Color by group Map groups to colors and build the legend by hand color="trade"
Progress, milestones, arrows Full control with overlays and annotate Possible with extra traces and shapes, more work
Best for Reports, slides, print Dashboards and web pages

Use Matplotlib when the chart goes in a document or needs custom marks. Use Plotly when people will explore it in a browser.

Practical Tips

  • Sort before plotting: rows appear in DataFrame order. df.sort_values("start") gives the usual staircase shape.
  • Long task names: layout="constrained" makes room for them on the left. For many tasks, increase the figure height by about 0.35 inches per row.
  • Long projects: switch the locator to mdates.MonthLocator() with DateFormatter("%b %Y"), or use mdates.ConciseDateFormatter to let Matplotlib choose.
  • Working days only: compute end dates with pd.offsets.BDay (for example df["start"] + pd.offsets.BDay(5)) when durations are in business days.
  • Export for print: fig.savefig("schedule.pdf") keeps the bars and text as vectors. The savefig post covers DPI and transparent backgrounds.

Similar Topics