How to Add a Table to a Matplotlib Plot

Put a data table under or beside a Matplotlib chart with ax.table(), then control its size, fonts, colors, and column widths.

To add a table to a Matplotlib figure, call ax.table() with cellText (a list of rows), and optionally colLabels and rowLabels. Use bbox=[left, bottom, width, height] to say exactly where it goes, in axes coordinates.

Quick Example

A line chart with the underlying numbers in a table beneath it:

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
visits = {
    "Organic": [31, 34, 39, 45, 48, 56],
    "Paid": [18, 22, 21, 25, 31, 29],
    "Referral": [9, 8, 12, 13, 15, 18],
}
colors = ["#2a9d8f", "#e76f51", "#8d6cab"]

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
for (source, values), color in zip(visits.items(), colors):
    ax.plot(months, values, marker="o", color=color, linewidth=2.5)

ax.table(
    cellText=list(visits.values()),
    rowLabels=list(visits),
    rowColours=colors,
    colLabels=months,
    cellLoc="center",
    bbox=[0, -0.36, 1, 0.28],  # below the plot, same width
)
ax.set_xlim(-0.5, len(months) - 0.5)  # center each point over its column
ax.set_xticks([])
ax.set_ylabel("Visits (thousands)")
ax.set_title("Website traffic by source")
plt.show()

Line chart of organic, paid and referral visits from January to June with a table of the monthly values directly beneath, row labels colored to match the lines

Setting the x limits to half a step beyond the first and last points lines each month up with its table column. The colored row labels act as the legend.

Place the Table With loc or bbox

loc picks a preset position: "bottom" (the default), "top", "center", "upper right", "left", "right", and others. The table takes its size from the font and column widths.

bbox overrides loc and sets the exact rectangle. [0, 0, 1, 1] fills the axes, negative values go below or left of it, and values above 1 go above or right.

A Table on Its Own

To render a table as an image with no chart, turn the axes off and fill it:

rows = [
    ["Laptop", "1.3 kg", "17 h", "$1,299"],
    ["Tablet", "0.5 kg", "11 h", "$649"],
    ["Phone", "0.2 kg", "22 h", "$899"],
    ["Watch", "0.04 kg", "36 h", "$399"],
]

fig, ax = plt.subplots(figsize=(7, 2.2), layout="constrained")
ax.axis("off")
ax.table(cellText=rows, colLabels=["Device", "Weight", "Battery", "Price"],
         cellLoc="center", bbox=[0, 0, 1, 1])
plt.show()

Plain table of four devices with their weight, battery life and price

Set Font Size, Row Height, and Column Width

Tables choose their own font size to fit the cells. To set it yourself, call auto_set_font_size(False) first. scale(x, y) stretches cell widths and heights, which is the usual fix for cramped rows:

fig, ax = plt.subplots(figsize=(7, 2.6), layout="constrained")
ax.axis("off")
table = ax.table(cellText=rows, colLabels=["Device", "Weight", "Battery", "Price"],
                 colWidths=[0.34, 0.2, 0.2, 0.2], cellLoc="left", loc="center")
table.auto_set_font_size(False)
table.set_fontsize(13)
table.scale(1, 1.9)
plt.show()

The device table with larger text, taller rows, a wider first column and left-aligned cells

colWidths are fractions of the axes width. table.auto_set_column_width([0, 1, 2, 3]) sizes columns to their text instead. scale() has no effect on size when you pass bbox, since the table is then fitted to that rectangle.

Style Headers, Rows, and Borders

ax.table() returns a Table whose cells are addressed by (row, column). Row 0 is the header when you pass colLabels, and row labels are in column -1.

fig, ax = plt.subplots(figsize=(7, 2.4), layout="constrained")
ax.axis("off")
table = ax.table(cellText=rows, colLabels=["Device", "Weight", "Battery", "Price"],
                 cellLoc="center", bbox=[0, 0, 1, 1])
table.auto_set_font_size(False)
table.set_fontsize(12)

for (row, col), cell in table.get_celld().items():
    cell.set_edgecolor("white")
    cell.set_linewidth(2)
    if row == 0:
        cell.set_facecolor("#1d3557")
        cell.set_text_props(color="white", fontweight="bold")
    elif row % 2 == 0:
        cell.set_facecolor("#e2e8f0")
    else:
        cell.set_facecolor("#f8fafc")

# Highlight the longest battery life
table[4, 2].set_facecolor("#b7e4c7")
table[4, 2].set_text_props(fontweight="bold")
plt.show()

Styled table with a navy header, alternating row shading, white dividers and the 36 hour battery cell highlighted in green

To remove borders, pass edges="horizontal" or edges="open" to ax.table(). Cells without a closed border aren't filled, so use this for unshaded tables:

fig, ax = plt.subplots(figsize=(7, 2.4), layout="constrained")
ax.axis("off")
ax.table(cellText=rows, colLabels=["Device", "Weight", "Battery", "Price"],
         cellLoc="center", bbox=[0, 0, 1, 1], edges="horizontal")
plt.show()

The device table drawn with horizontal lines only

Color Cells by Value

Pass a 2D list or array of colors as cellColours. A colormap turns numbers into colors:

import numpy as np

scores = np.array([[72, 88, 65], [91, 79, 84], [58, 67, 93], [83, 95, 76]])
shades = plt.cm.YlGn((scores - 40) / 70)  # keep text readable on the darkest cell

fig, ax = plt.subplots(figsize=(6.5, 2.4), layout="constrained")
ax.axis("off")
ax.table(cellText=scores, cellColours=shades,
         rowLabels=["Ana", "Ben", "Chi", "Dev"],
         colLabels=["Math", "Writing", "Science"],
         cellLoc="center", bbox=[0.1, 0, 0.9, 1])
plt.show()

Table of test scores for four students in three subjects, with darker green for higher scores

For a larger grid, an annotated heatmap does this with less work.

Draw a pandas DataFrame as a Table

Pass the values, index, and columns separately. Format numbers into strings first, because the table prints exactly what you give it:

import pandas as pd

df = pd.DataFrame(
    {"Revenue": [1_204_500, 986_200, 1_430_900], "Margin": [0.214, 0.187, 0.263]},
    index=["North", "South", "West"])

text = pd.DataFrame({
    "Revenue": df["Revenue"].map("${:,.0f}".format),
    "Margin": df["Margin"].map("{:.1%}".format),
})

fig, ax = plt.subplots(figsize=(8, 3.4), layout="constrained")
ax.barh(df.index, df["Revenue"] / 1e6, color="#457b9d")
ax.invert_yaxis()
ax.set_xlabel("Revenue ($ millions)")
ax.table(cellText=text.values, rowLabels=text.index, colLabels=text.columns,
         cellLoc="right", bbox=[1.14, 0.2, 0.55, 0.6])
plt.show()

Horizontal bar chart of revenue for three regions with a table of revenue and margin to its right

pandas.plotting.table(ax, df) is a shortcut that reads the labels from the DataFrame.

ax.table or Great Tables?

ax.table() is the right tool when the table belongs to a chart. It has no number formatting, column groups, or text wrapping. For a table that stands alone in a report, use Great Tables or the pandas Styler.

When saving, pass bbox_inches="tight" to savefig() so a table outside the axes isn't cut off.

Similar Topics