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
How to assign specific colors to specific cells in a Matplotlib table?
Matplotlib allows you to assign specific colors to individual cells in a table using the cellColours parameter. This is useful for highlighting data, creating color-coded reports, or improving table readability.
Basic Syntax
The ax.table() method accepts a cellColours parameter that takes a 2D list where each element corresponds to a cell color ?
ax.table(cellText=data, cellColours=colors, colLabels=columns, loc='center')
Example
Let's create a table with employee data and assign specific colors to each cell ?
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Define column headers
columns = ('Name', 'Age', 'Marks', 'Salary')
# Data for the table
cell_text = [["John", "23", "98", "234"],
["James", "24", "90", "239"]]
# Colors for each cell (corresponding to cell_text positions)
colors = [["lightcoral", "lightyellow", "lightblue", "lightgreen"],
["lightblue", "lightgreen", "lightyellow", "lightcoral"]]
# Create figure and subplot
fig, ax = plt.subplots()
# Create table with colored cells
the_table = ax.table(cellText=cell_text,
cellColours=colors,
colLabels=columns,
loc='center')
# Turn off axis
ax.axis('off')
# Display the table
plt.show()
Using Different Color Formats
You can specify colors using various formats: color names, hex codes, or RGB tuples ?
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [8, 4]
plt.rcParams["figure.autolayout"] = True
columns = ('Product', 'Price', 'Stock')
cell_text = [["Laptop", "$999", "15"],
["Phone", "$599", "8"],
["Tablet", "$399", "22"]]
# Different color formats
colors = [["#FF6B6B", "#4ECDC4", "#45B7D1"], # Hex codes
["#96CEB4", "#FFEAA7", "#DDA0DD"], # More hex codes
["#98D8C8", "#F7DC6F", "#BB8FCE"]] # Even more hex codes
fig, ax = plt.subplots()
the_table = ax.table(cellText=cell_text,
cellColours=colors,
colLabels=columns,
loc='center')
# Adjust table appearance
the_table.auto_set_font_size(False)
the_table.set_fontsize(12)
the_table.scale(1.2, 1.8)
ax.axis('off')
plt.show()
Key Points
- cellColours must be a 2D list matching the dimensions of your data
- Colors can be specified as names, hex codes, or RGB tuples
- Use
loc='center'to center the table in the subplot - Call
ax.axis('off')to hide the coordinate axes
Conclusion
The cellColours parameter in Matplotlib's table() function provides an easy way to assign specific colors to individual cells. This feature is particularly useful for creating visually appealing data presentations and highlighting important information in tables.
