How can I place a table on a plot in Matplotlib?

Matplotlib allows you to add tables directly to plots using the table() method. This is useful for displaying data alongside visualizations or creating standalone table presentations.

Basic Table Creation

First, let's create a simple table using a Pandas DataFrame ?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create figure and axis
fig, ax = plt.subplots(figsize=(8, 6))

# Create sample data
df = pd.DataFrame({
    'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor'],
    'Price': [899, 25, 79, 299],
    'Stock': [15, 50, 30, 8]
})

# Add table to the plot
table = ax.table(cellText=df.values,
                colLabels=df.columns,
                cellLoc='center',
                loc='center')

# Remove axes
ax.axis('off')

plt.title('Product Inventory Table')
plt.show()

Customizing Table Appearance

You can customize colors, fonts, and cell properties by iterating through table cells ?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create figure and axis
fig, ax = plt.subplots(figsize=(10, 6))

# Create sample data with datetime
df = pd.DataFrame({
    'Date': pd.date_range('2024-01-01', periods=5),
    'Sales': [1200, 1450, 980, 1680, 1320],
    'Profit': [240, 290, 196, 336, 264]
})

# Add table to the plot
mpl_table = ax.table(cellText=df.values,
                    colLabels=df.columns,
                    cellLoc='center',
                    loc='center',
                    bbox=[0, 0, 1, 1])

# Customize table appearance
mpl_table.auto_set_font_size(False)
mpl_table.set_fontsize(11)
mpl_table.scale(1, 2)

# Style individual cells
for (row, col), cell in mpl_table.get_celld().items():
    cell.set_edgecolor('black')
    cell.set_linewidth(1)
    
    if row == 0:  # Header row
        cell.set_text_props(weight='bold', color='white')
        cell.set_facecolor('#4CAF50')
    else:  # Data rows
        if col == 0:  # First column
            cell.set_facecolor('#E8F5E8')
        else:
            cell.set_facecolor(['#F0F8FF', '#F5F5F5'][row % 2])

# Remove axes
ax.axis('off')
plt.title('Sales Report', fontsize=16, fontweight='bold', pad=20)
plt.tight_layout()
plt.show()

Table with Plot Combination

You can combine tables with plots by using subplots ?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create sample data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [1200, 1450, 980, 1680, 1320]

df = pd.DataFrame({'Month': months, 'Sales': sales})

# Create subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))

# Plot data
ax1.bar(months, sales, color='skyblue', edgecolor='navy')
ax1.set_title('Monthly Sales Chart')
ax1.set_ylabel('Sales ($)')

# Add table below the plot
table = ax2.table(cellText=df.values,
                 colLabels=df.columns,
                 cellLoc='center',
                 loc='center')

table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1, 1.5)

# Style the table
for (row, col), cell in table.get_celld().items():
    if row == 0:
        cell.set_facecolor('#40466e')
        cell.set_text_props(weight='bold', color='white')
    else:
        cell.set_facecolor('#f1f1f2')

ax2.axis('off')
ax2.set_title('Sales Data Table')

plt.tight_layout()
plt.show()

Key Parameters

Parameter Description Example Values
cellText Data for table cells df.values
colLabels Column headers df.columns
cellLoc Text alignment in cells 'center', 'left', 'right'
loc Table position 'center', 'upper right'
bbox Table boundaries [x, y, width, height]

Conclusion

Use ax.table() to add tables to Matplotlib plots. Customize appearance by iterating through get_celld().items() to modify individual cells. Combine with axis('off') for clean table presentations.

Updated on: 2026-03-25T19:48:30+05:30

886 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements