I Want to change a font size of specific cells using Python matplotlib. But when i try it, all cells of the table is changed..
Here is my code.
# 1. Define the variable
import matplotlib.pyplot as plt
from matplotlib.table import Table
# Dummy data
data = [["Name", "Age", "Affiliation"],
["Bam", "12", "didoda"],
["Gireogi", "13", "Jadory"]]
# Define rows and columns
n_rows, n_cols = len(data), len(data[0])
width, height = 1.0 / n_cols, 1.0 / n_rows
# 2. Import Table and create figure
fig, ax = plt.subplots(figsize=(6, 3))
ax.axis('tight')
ax.axis('off')
table = Table(ax, bbox=[0, 0, 1, 1])
# 4. Add dummy data as cells
for i in range(n_rows):
for j in range(n_cols):
cell_text = data[i][j]
table.add_cell(i, j, width, height, text=cell_text, loc='center', edgecolor='black')
# 3. Refer to what I want to change (specific cell)
cell = table.get_celld()[(1, 2)] # Access cell at row 1, column 2
print(type(cell)) # Confirm the cell type
cell.set_fontsize(3.5) # Adjust font size for this specific cell
# Add the table to the axis
ax.add_table(table)
# Display the table
plt.show()
I dont know why it works like this.
Definitely, i use the method of Cell object, which is set_fontsize. i keep the size of all the cells in 20px except a cell at row 1, column 2. i wanna change the cell at row 1, column 2 (written “didoda”) like 3.5. Why does it change all the cell of the table?
enter image description here
Over the image is the result in this code.
import matplotlib.pyplot as plt
from matplotlib.table import Table
# Dummy data
data = [["Name", "Age", "Affiliation"],
["Bam", "12", "didoda"],
["Gireogi", "13", "Jadory"]]
# Define rows and columns
n_rows, n_cols = len(data), len(data[0])
width, height = 1.0 / n_cols, 1.0 / n_rows
# 2. Import Table and create figure
fig, ax = plt.subplots(figsize=(6, 3))
ax.axis('tight')
ax.axis('off')
table = Table(ax, bbox=[0, 0, 1, 1])
# 4. Add dummy data as cells
for i in range(n_rows):
for j in range(n_cols):
cell_text = data[i][j]
table.add_cell(i, j, width, height, text=cell_text, loc='center', edgecolor='black')
cell.set_fontsize(10) # Default font size
# Modify specific cells with different font sizes
specific_cells = {
(1, 1): 10, # Row 1, Column 1 - Small font
(1, 2): 14 # Row 1, Column 2 - Large font
}
# Apply specific font sizes
for (row, col), size in specific_cells.items():
cell = table.get_celld()[(row, col)]
# Update the font size only
cell._text.set_fontsize(size) # This will change only the specified cell's font size
# Add the table to the axis
ax.add_table(table)
# Display the table
plt.show()
You need to use table.auto_set_font_size(False)
before use set font size of the specific cell, so your code should look like:
...
table.auto_set_font_size(False)
cell = table.get_celld()[(1, 2)] # Access cell at row 1, column 2
print(type(cell)) # Confirm the cell type
cell.set_fontsize(3.5) # Adjust font size for this specific cell