Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding a data table to the figure using Python
In this article, we will learn how to add a data table to the figure using Python.
Although matplotlib is primarily a plotting library, it also assists us with minor tasks when making a chart, such as having a nice data table alongside our attractive visuals.
It is critical to understand why we are adding a table to a plot. The primary goal of plotting data visually is to clarify the otherwise incomprehensible data values. However, properly chosen, perhaps summarized, or highlighted values from the entire dataset might identify essential areas of the chart or highlight important values where exact precision is required (for example, yearly sales in USD).
Creating a Basic Plot with Data Table
Let's start with a simple example that combines a line plot with a data table ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [120, 135, 98, 165, 180, 142]
# Create the plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(months, sales, marker='o', linewidth=2, markersize=8)
ax.set_title('Monthly Sales Data', fontsize=14, fontweight='bold')
ax.set_ylabel('Sales (in thousands)')
# Create table data
table_data = [
['Jan', '120k'],
['Feb', '135k'],
['Mar', '98k'],
['Apr', '165k'],
['May', '180k'],
['Jun', '142k']
]
# Add table to the plot
table = ax.table(cellText=table_data,
colLabels=['Month', 'Sales'],
cellLoc='center',
loc='center right',
bbox=[1.05, 0.2, 0.3, 0.6])
table.auto_set_font_size(False)
table.set_fontsize(9)
table.scale(1, 1.5)
plt.tight_layout()
plt.show()
Adding Colored Table with Custom Styling
We can enhance our table with colors and custom formatting ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
categories = ['Product A', 'Product B', 'Product C', 'Product D']
values = [45, 32, 67, 28]
# Create bar plot
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(categories, values, color=['skyblue', 'lightgreen', 'lightcoral', 'gold'])
ax.set_title('Product Performance', fontsize=14, fontweight='bold')
ax.set_ylabel('Performance Score')
# Prepare table data with statistics
table_data = [
['Product A', '45', 'Good'],
['Product B', '32', 'Average'],
['Product C', '67', 'Excellent'],
['Product D', '28', 'Below Average']
]
# Define colors for rows
row_colors = ['lightblue', 'lightgray', 'lightgreen', 'lightyellow']
# Add styled table
table = ax.table(cellText=table_data,
colLabels=['Product', 'Score', 'Rating'],
rowColours=row_colors,
colColours=['lightsteelblue'] * 3,
cellLoc='center',
loc='upper left',
bbox=[0.02, 0.6, 0.35, 0.35])
table.auto_set_font_size(False)
table.set_fontsize(9)
table.scale(1, 1.8)
plt.tight_layout()
plt.show()
Table with Summary Statistics
Here's an example that shows how to add a summary table with calculated statistics ?
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
np.random.seed(42)
data = np.random.normal(50, 15, 100)
# Create histogram
fig, ax = plt.subplots(figsize=(12, 6))
n, bins, patches = ax.hist(data, bins=20, alpha=0.7, color='steelblue', edgecolor='black')
ax.set_title('Data Distribution with Summary Statistics', fontsize=14, fontweight='bold')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
# Calculate statistics
mean_val = np.mean(data)
median_val = np.median(data)
std_val = np.std(data)
min_val = np.min(data)
max_val = np.max(data)
# Prepare summary table
summary_data = [
['Mean', f'{mean_val:.2f}'],
['Median', f'{median_val:.2f}'],
['Std Dev', f'{std_val:.2f}'],
['Minimum', f'{min_val:.2f}'],
['Maximum', f'{max_val:.2f}'],
['Count', f'{len(data)}']
]
# Add summary table
table = ax.table(cellText=summary_data,
colLabels=['Statistic', 'Value'],
cellLoc='center',
loc='upper right',
bbox=[0.7, 0.6, 0.28, 0.35])
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1, 1.5)
# Style the table
for i in range(len(summary_data)):
table[(i+1, 0)].set_facecolor('lightgray')
table[(i+1, 1)].set_facecolor('white')
plt.tight_layout()
plt.show()
Key Parameters of plt.table()
The plt.table() function accepts several important parameters ?
| Parameter | Description | Example Values |
|---|---|---|
cellText |
2D array of cell values | [['A', '1'], ['B', '2']] |
colLabels |
Column header labels | ['Name', 'Value'] |
rowLabels |
Row header labels | ['Row1', 'Row2'] |
loc |
Table position |
'upper right', 'center'
|
cellLoc |
Text alignment in cells |
'center', 'left', 'right'
|
rowColours |
Row background colors | ['red', 'blue', 'green'] |
Best Practices
Keep tables concise: Only include essential data that complements the visualization.
Use appropriate positioning: Place tables where they don't obstruct the main plot elements.
Apply consistent formatting: Use colors and fonts that match your plot's style.
Consider readability: Ensure text size and colors provide good contrast and visibility.
Conclusion
Adding data tables to matplotlib figures enhances data presentation by combining visual appeal with precise numerical values. Use plt.table() with appropriate styling and positioning to create informative and professional-looking visualizations that serve both analytical and presentation purposes.
