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 change the transparency/opaqueness of a Matplotlib Table?
In Matplotlib, you can control the transparency (alpha value) of table cells to create visually appealing tables. The set_alpha() method allows you to adjust opacity, where 0.0 is completely transparent and 1.0 is completely opaque.
Steps to Change Table Transparency
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Create a random dataset with 10×3 dimension.
Create a tuple of columns.
Get rid of the axis markers using
axis('off').Create a table with data and columns.
Iterate each cell of the table and change its transparency using
set_alpha()method.Display the figure using
show()method.
Example
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axs = plt.subplots(1, 1)
data = np.random.random((10, 3))
columns = ("Column I", "Column II", "Column III")
axs.axis('off')
the_table = axs.table(cellText=data, colLabels=columns, loc='center')
for k, cell in the_table._cells.items():
cell.set_edgecolor('black')
if k[0] == 0 or k[1] < 0:
cell.set_text_props(weight='bold', color='w')
cell.set_facecolor('red')
cell.set_alpha(0.5)
else:
cell.set_facecolor(['green', 'yellow'][k[0] % 2])
cell.set_alpha(0.5)
plt.show()
Understanding Alpha Values
The set_alpha() method accepts values between 0.0 and 1.0 ?
import numpy as np
from matplotlib import pyplot as plt
fig, axs = plt.subplots(1, 1)
data = [['Transparent', 'Semi-transparent', 'Opaque']]
columns = ('Alpha=0.2', 'Alpha=0.5', 'Alpha=1.0')
axs.axis('off')
the_table = axs.table(cellText=data, colLabels=columns, loc='center')
# Set different alpha values for demonstration
alpha_values = [0.2, 0.5, 1.0]
for i, (k, cell) in enumerate(the_table._cells.items()):
if k[0] == 0: # Header row
cell.set_facecolor('blue')
cell.set_text_props(weight='bold', color='white')
cell.set_alpha(alpha_values[k[1]])
else: # Data row
cell.set_facecolor('lightblue')
cell.set_alpha(alpha_values[k[1]])
plt.title('Table Transparency Examples')
plt.show()
Key Points
Alpha = 0.0: Completely transparent (invisible)
Alpha = 0.5: Semi-transparent (50% opacity)
Alpha = 1.0: Completely opaque (default)
Use
the_table._cells.items()to iterate through all table cellsCell coordinates are stored as tuples (row, column) where row 0 is the header
Conclusion
Use the set_alpha() method to control table cell transparency in Matplotlib. Values range from 0.0 (transparent) to 1.0 (opaque), allowing you to create layered visual effects and improve table readability.
