# How to Make a GitHub-Style Contribution Heatmap in Python

> Build a GitHub-style contribution graph (calendar heatmap) in Python. Covers the weekday-by-week grid in pandas, a Matplotlib version with discrete green levels, rounded squares and a dark theme, calplot, Plotly, and your own git log data.

Source: https://www.pythoncharts.com/python/github-contribution-heatmap-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Python | Tags: matplotlib, plotly, calendar heatmap, heatmap, calplot, time series, pandas

A GitHub-style contribution graph is a calendar heatmap: one small square per day, arranged in columns by week and rows by weekday, and colored by how much happened that day. To build one in Python, compute each date's week number and weekday with pandas, pivot the daily counts into a 7-row grid, and draw it with Matplotlib's `pcolormesh` using a few discrete shades of green. For a one-liner, the `calplot` package does the same thing, and Plotly's `go.Heatmap` gives you an interactive version with hover tooltips.

## Quick Example

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import BoundaryNorm, ListedColormap

# Sample data: one year of daily commit counts
def fake_commits(start, end, seed):
    """Busier on weekdays, some idle days, a few bursts."""
    rng = np.random.default_rng(seed)
    days = pd.date_range(start, end, freq="D")
    rate = np.where(days.dayofweek < 5, 4.0, 0.8) * rng.gamma(2, 0.7, len(days))
    active = rng.random(len(days)) < 0.7
    return pd.Series(rng.poisson(rate) * active, index=days, name="commits")

counts = fake_commits("2026-01-01", "2026-12-31", seed=2026)

# Arrange the days into a 7 x n_weeks grid (rows = weekday with Sunday on top, cols = week)
days = counts.index
start = days[0] - pd.Timedelta(days=(days[0].dayofweek + 1) % 7)  # Sunday on/before Jan 1
grid = pd.DataFrame({
    "count": counts.values,
    "weekday": (days.dayofweek + 1) % 7,          # Sun=0 ... Sat=6
    "week": (days - start).days // 7,
}).pivot(index="weekday", columns="week", values="count")

# Five discrete levels, GitHub's light-theme greens
colors = ["#ebedf0", "#9be9a8", "#40c463", "#30a14e", "#216e39"]
cmap = ListedColormap(colors)
norm = BoundaryNorm([0, 1, 3, 6, 10, np.inf], cmap.N)

fig, ax = plt.subplots(figsize=(13, 2.6))
ax.pcolormesh(np.ma.masked_invalid(grid.values), cmap=cmap, norm=norm,
              edgecolors="white", linewidth=2)
ax.set_aspect("equal")
ax.invert_yaxis()
ax.set_yticks([1.5, 3.5, 5.5], ["Mon", "Wed", "Fri"])
month_starts = pd.date_range("2026-01-01", "2026-12-01", freq="MS")
ax.set_xticks((month_starts - start).days // 7 + 0.5, month_starts.strftime("%b"))
ax.xaxis.tick_top()
ax.tick_params(length=0, labelsize=9)
for spine in ax.spines.values():
    spine.set_visible(False)
ax.set_title(f"{counts.sum():,} commits in 2026", loc="left", fontsize=11, pad=22)
plt.show()
```

![GitHub-style contribution heatmap made with Matplotlib: 53 weekly columns by 7 weekday rows of squares shaded from light gray to dark green, showing 1,006 commits in 2026 with weekends mostly light](https://www.pythoncharts.com/python/github-contribution-heatmap-python/images/github-heatmap-quick-example.png)

Each column is a week and each row a day of the week, with Sunday at the top like GitHub. Gray squares are days with no commits, and darker greens mean busier days. Weekdays are clearly busier than the top and bottom (weekend) rows. The code uses pandas 2/3 and Matplotlib 3.8 or newer.

## How the Calendar Grid Works

The only tricky part is mapping each date to a (row, column) cell:

- **Row (weekday):** pandas' `dayofweek` is Monday=0 … Sunday=6. GitHub puts Sunday first, so `(dayofweek + 1) % 7` turns that into Sunday=0 … Saturday=6. For a Monday-first calendar, use `dayofweek` directly.
- **Column (week):** count whole weeks since the Sunday on or before the first date: `(date - start).days // 7`. Every Sunday starts a new column, so the year usually spans 53 columns.

`pivot` then turns the long table into a 7 × 53 grid. Days outside the range, such as the Sunday through Wednesday before January 1, 2026 (a Thursday), become `NaN`. `np.ma.masked_invalid` masks them so `pcolormesh` leaves those cells empty rather than coloring them. `edgecolors="white", linewidth=2` draws the gaps between squares, and `ax.set_aspect("equal")` keeps them square.

## Use Discrete Color Levels Instead of a Continuous Colormap

GitHub doesn't use a smooth gradient. Every day falls into one of five buckets: none, and four levels of activity. That reads better than a continuous colormap, where one 40-commit day would wash every normal day out to the palest color.

`BoundaryNorm` does the bucketing. With boundaries `[0, 1, 3, 6, 10, inf]` and five colors:

| Commits that day | Level | Color |
|---|---|---|
| 0 | 0 | `#ebedf0` (gray) |
| 1–2 | 1 | `#9be9a8` |
| 3–5 | 2 | `#40c463` |
| 6–9 | 3 | `#30a14e` |
| 10+ | 4 | `#216e39` |

Pick thresholds that suit your data. GitHub scales them to each user's activity, roughly by quartiles of their non-zero days. You can do the same with `np.quantile(counts[counts > 0], [0.25, 0.5, 0.75])` and use the results as the middle boundaries. For more on building colormaps like this, see [Custom Colormaps in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-custom-colormaps/).

## Match the GitHub Look: Rounded Squares and a "Less/More" Legend

`pcolormesh` draws sharp rectangles. For GitHub's rounded squares, draw each day as a `FancyBboxPatch` instead, and add the small "Less ▢▢▢▢▢ More" legend under the bottom-right corner. Wrapping it in a function also makes it reusable for any daily series:

```python
from matplotlib.patches import FancyBboxPatch

THEMES = {
    "light": dict(bg="#ffffff", text="#1f2328", muted="#59636e",
                  levels=["#ebedf0", "#9be9a8", "#40c463", "#30a14e", "#216e39"]),
    "dark": dict(bg="#0d1117", text="#f0f6fc", muted="#9198a1",
                 levels=["#151b23", "#033a16", "#196c2e", "#2ea043", "#56d364"]),
}

def github_heatmap(counts, ax, theme="light", thresholds=(1, 3, 6, 10)):
    t = THEMES[theme]
    days = counts.index
    start = days[0] - pd.Timedelta(days=(days[0].dayofweek + 1) % 7)
    weeks = (days - start).days // 7
    weekdays = (days.dayofweek + 1) % 7
    levels = np.digitize(counts.values, thresholds)  # 0 = no activity, 4 = busiest

    for w, d, lvl in zip(weeks, weekdays, levels):
        ax.add_patch(FancyBboxPatch(
            (w + 0.1, d + 0.1), 0.8, 0.8,
            boxstyle="round,pad=0,rounding_size=0.15",
            facecolor=t["levels"][lvl], edgecolor="none",
        ))

    n_weeks = weeks.max() + 1
    ax.set_xlim(-0.1, n_weeks + 0.1)
    ax.set_aspect("equal")
    ax.axis("off")

    for day, label in [(1, "Mon"), (3, "Wed"), (5, "Fri")]:
        ax.text(-0.5, day + 0.5, label, ha="right", va="center", fontsize=8, color=t["muted"])
    for m in pd.date_range(days[0], days[-1], freq="MS"):
        ax.text((m - start).days // 7, -0.6, m.strftime("%b"), fontsize=8, color=t["muted"])

    # "Less [] [] [] [] [] More" legend under the bottom-right corner
    x0 = n_weeks - 8.5
    ax.text(x0 - 0.4, 8.0, "Less", ha="right", va="center", fontsize=8, color=t["muted"])
    for i, color in enumerate(t["levels"]):
        ax.add_patch(FancyBboxPatch((x0 + i + 0.1, 7.6), 0.8, 0.8,
                                    boxstyle="round,pad=0,rounding_size=0.15",
                                    facecolor=color, edgecolor="none", clip_on=False))
    ax.text(x0 + 5.2, 8.0, "More", ha="left", va="center", fontsize=8, color=t["muted"])
    ax.set_ylim(8.6, -1.2)  # inverted, so Sunday is on top

    ax.set_title(f"{counts.sum():,} contributions in {days[0].year}",
                 loc="left", fontsize=11, color=t["text"])
    ax.figure.set_facecolor(t["bg"])

fig, ax = plt.subplots(figsize=(13, 2.6))
github_heatmap(counts, ax, theme="light")
fig.savefig("contributions.png", dpi=130, bbox_inches="tight", facecolor=fig.get_facecolor())
```

![Polished GitHub-style contribution graph in Matplotlib with rounded green squares, month and weekday labels, a 1,006 contributions in 2026 title, and a Less to More color legend](https://www.pythoncharts.com/python/github-contribution-heatmap-python/images/github-heatmap-light.png)

`np.digitize(counts, (1, 3, 6, 10))` returns the level (0–4) for each day using the same buckets as the table above. Each square is 0.8 units wide inside a 1-unit cell, which leaves the gaps. Because the axes are inverted (`set_ylim(8.6, -1.2)`), row 0 (Sunday) is on top, the month labels at y = -0.6 sit above the grid, and the legend at y ≈ 8 sits below it.

### Dark mode

Pass `theme="dark"` to swap in GitHub's dark background and its brighter greens:

```python
fig, ax = plt.subplots(figsize=(13, 2.6))
github_heatmap(counts, ax, theme="dark")
fig.savefig("contributions-dark.png", dpi=130, bbox_inches="tight", facecolor=fig.get_facecolor())
```

![Dark-mode GitHub-style contribution heatmap with near-black background, dark gray empty days, and bright green busy days](https://www.pythoncharts.com/python/github-contribution-heatmap-python/images/github-heatmap-dark.png)

In the dark theme the busiest days are the *brightest* green rather than the darkest, so busy days still stand out against the background. Pass `facecolor=fig.get_facecolor()` to `savefig` so the saved file keeps the dark background. The [savefig guide](https://www.pythoncharts.com/matplotlib/matplotlib-savefig/) covers the other export options.

## The Shortcut: calplot

The [`calplot`](https://github.com/tomkwok/calplot) package (`pip install calplot`) draws calendar heatmaps from a date-indexed pandas Series in one call, with one row per year:

```python
import calplot

two_years = fake_commits("2025-01-01", "2026-12-31", seed=7)
fig, axes = calplot.calplot(two_years, cmap="Greens", colorbar=True,
                            edgecolor=None, linewidth=2, linecolor="white",
                            fillcolor="#ebedf0", figsize=(13, 4),
                            suptitle="Daily commits, 2025-2026")
```

![calplot calendar heatmap with one row per year for 2025 and 2026, green squares by day with Monday through Sunday rows and a colorbar from 0 to 20 commits](https://www.pythoncharts.com/python/github-contribution-heatmap-python/images/github-heatmap-calplot.png)

Compared with the GitHub layout, `calplot` puts Monday on top, labels each year down the left side, and uses a continuous colormap with a colorbar. It aggregates for you as well: pass timestamped events with `how="count"` or a daily series with the default `how="sum"`. Use it for quick multi-year overviews, and the Matplotlib version when you need exact control over the look. Another package, `july`, offers a `cmap="github"` preset, but it fails on current Matplotlib releases (it references `matplotlib.cbook.MatplotlibDeprecationWarning`, which has been removed).

## An Interactive Version with Plotly

In Plotly, the same 7 × 53 grid goes into `go.Heatmap`. `xgap`/`ygap` create the gaps between squares, and `customdata` carries the date and count into the hover tooltip. Plotly has no `BoundaryNorm`, so pass the level (0–4) as `z` and build a colorscale with one flat band per level:

```python
import plotly.graph_objects as go

cells = pd.DataFrame({
    "weekday": (days.dayofweek + 1) % 7,
    "week": (days - start).days // 7,
    "level": np.digitize(counts.values, (1, 3, 6, 10)),
    "count": counts.values,
    "label": days.strftime("%a, %b %-d, %Y"),
})
z = cells.pivot(index="weekday", columns="week", values="level")
hover_counts = cells.pivot(index="weekday", columns="week", values="count")
hover_dates = cells.pivot(index="weekday", columns="week", values="label")

colorscale = []
for i, color in enumerate(colors):  # one flat band per level, so colors are discrete
    colorscale += [[i / 5, color], [(i + 1) / 5, color]]

fig = go.Figure(go.Heatmap(
    z=z.values,
    customdata=np.dstack([hover_dates.values, hover_counts.values]),
    hovertemplate="%{customdata[1]} commits on %{customdata[0]}<extra></extra>",
    colorscale=colorscale, zmin=-0.5, zmax=4.5, showscale=False,
    xgap=3, ygap=3,
))
fig.update_yaxes(tickvals=[1, 3, 5], ticktext=["Mon", "Wed", "Fri"],
                 autorange="reversed", scaleanchor="x", showgrid=False, zeroline=False)
fig.update_xaxes(tickvals=(month_starts - start).days // 7,
                 ticktext=month_starts.strftime("%b"), side="top",
                 showgrid=False, zeroline=False)
fig.update_layout(title_text=f"{counts.sum():,} commits in 2026",
                  plot_bgcolor="white", paper_bgcolor="white",
                  margin=dict(l=40, r=20, t=80, b=20))
fig.show()
```

![Interactive Plotly GitHub-style contribution heatmap with green squares for each day of 2026 and hover tooltips showing the date and commit count](https://www.pythoncharts.com/python/github-contribution-heatmap-python/images/github-heatmap-plotly.png)

Hover over any square to see its date and commit count. `zmin=-0.5, zmax=4.5` centers each integer level in its color band, and `scaleanchor="x"` keeps the cells square as the chart resizes. (`%-d` drops the leading zero from the day on macOS and Linux. On Windows, use `%#d`.) For more on tooltips, see [Customize Hover Tooltips in Plotly](https://www.pythoncharts.com/plotly/plotly-customize-hover-tooltips/).

## Plot Your Own Git History

Any daily count works: workouts, words written, sales, support tickets. To chart your own commits, pull the dates from `git log` and count them per day:

```python
import subprocess

dates = subprocess.run(
    ["git", "log", "--since=2026-01-01", "--pretty=format:%ad", "--date=short"],
    capture_output=True, text=True, check=True,
).stdout.split()

counts = (
    pd.Series(1, index=pd.to_datetime(dates))
    .groupby(level=0).sum()
    .reindex(pd.date_range("2026-01-01", "2026-12-31"), fill_value=0)
)
```

Run it inside a repository. Add `--author="you@example.com"` to count only your commits. `reindex` fills days with no commits with 0, so every day gets a square. The result plugs straight into the code above. For your full GitHub profile (all repositories, PRs, and issues), the GitHub GraphQL API exposes the same daily counts under `contributionsCollection.contributionCalendar`.

## Practical Tips

- Use 4–5 discrete levels, not a continuous colormap, so a few outlier days don't wash everything else out.
- Show empty days in a neutral gray rather than leaving them blank. "Nothing happened" is information.
- Keep the cells square with `set_aspect("equal")` (Matplotlib) or `scaleanchor="x"` (Plotly), and make the figure about five times wider than it is tall.
- For data spanning several years, draw one row of axes per year (or use `calplot`) instead of one very wide grid.
- If you need a correlation-style heatmap instead, see [How to Create Heatmaps in Matplotlib](https://www.pythoncharts.com/matplotlib/heatmaps-matplotlib/).

## Similar Topics

- [How to Create Heatmaps in Matplotlib](https://www.pythoncharts.com/matplotlib/heatmaps-matplotlib/)
- [Custom Colormaps in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-custom-colormaps/)
- [How to Create a Waffle Chart in Python using PyWaffle](https://www.pythoncharts.com/python/waffle-chart-pywaffle/)
