我想更改Python matplotlib中特定单元格的字体大小

问题描述 投票:0回答:1

我想使用 Python matplotlib 更改特定单元格的字体大小。但是当我尝试时,表格的所有单元格都改变了..

这是我的代码。

# 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()

我不知道为什么会这样。 当然,我使用的是Cell对象的方法,即set_fontsize。我将所有单元格的大小保持在 20px,除了第 1 行第 2 列的单元格。我想更改第 1 行第 2 列的单元格(写为“didoda”),如 3.5。为什么它会改变表格的所有单元格?

在此输入图片描述

图像上方是此代码的结果。

python
1个回答
0
投票
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()
© www.soinside.com 2019 - 2024. All rights reserved.