matplotlib 如何为带有彩色单元格的表格添加底部边框

bogh5gae  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(124)

我正在尝试为每个单元格添加底部边框。
我试过这段代码,但它重置了表的颜色:cell.visible_edges = 'B'

# Read the Excel file
excel_file = "/path"
df = pd.read_excel(excel_file, sheet_name='Sheet1')

# Filter out rows (axis = 0) and columns (axis = 1) with all NaN values
df = df.dropna(axis=0, how='all')
df = df.dropna(axis=1, how='all')

# Create a table-like visualization using matplotlib
fig, ax = plt.subplots(figsize=(16, 10))
ax.axis('off')  # Turn off the axis

# Plot the table with colored cells, without cell borders and without headers
tab = ax.table(cellText=df.values, cellLoc='center', loc='center')

columns_to_adjust = [0, 1]  # List of column indices to adjust
for i in range(len(df.iloc[:, 0])):
    for col_index in columns_to_adjust:
        cell = tab[(i + 0, col_index)] # Loop through each non-empty cell in both columns
        cell_text = cell.get_text().get_text() # Get text from the cell
        cell.get_text().set_horizontalalignment('left') # Left alignment
        cell.set_height(0.04) # Set the height
        cell = tab[(i + 0, 0)] # Loop through each non-empty cell in column 1
        cell.set_width(0.45) # Set width
        if "ABC" in cell_text:
            cell.get_text().set_color('white')  # Set font color to white
            cell.set_facecolor('blue') # Set background color to blue
        cell.PAD = 0.025 # Adjust spacing between the beginning of the cell and the text
        cell = tab[(i + 0, 1)] # Loop through each non-empty cell in column 2   
        cell.set_width(0.035)  # Set width
os8fio9y

os8fio9y1#

我将pandas.DataFrame替换为包含任意数据的numpy.array
matplotlib在多个版本中似乎有一个bug(我测试了v3.5.1和v3.7.2)。实际问题不是在彩色单元格上添加边框,而是当你没有在所有四个侧面使用单元格边框时,正确渲染单元格颜色。
下面是github上的相应讨论:https://github.com/matplotlib/matplotlib/issues/20100
您可以通过两次绘制同一个表来创建解决方法:

  • 表1颜色和edges = 'BTLR'以及线宽设置为零
  • 表2中包含您所需的edges

范例:

import matplotlib.pyplot as plt
import numpy as np

## generate some data + colors to display
sample_data = np.array([
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i']])
sample_colors = np.array([
    ['#444444', '#555555', '#666666'],
    ['#777777', '#FF00FF', '#999999'],
    ['#AAAAAA', '#BBBBBB', '#CCCCCC']])

## create subplot
ax = plt.subplot()
ax.axis('off')  # Turn off the axis

## create table1 -> cell colors
table1 = ax.table(
    cellText=sample_data,
    cellColours=sample_colors, ## configure cell colors
    cellLoc='center',
    loc='center',
    edges = 'BTLR') ## necessary to render the cell colors

## set linewidth of table1 to zero (invisible cell borders)
for x in table1.properties()['celld'].values():
    x.set(linewidth=0)

## create table2 -> cell borders
table2 = ax.table(
    cellText=sample_data,
    cellLoc='center',
    loc='center',
    edges = 'B') ## actual cell borders (bottom-top-left-right)

## display result
plt.show()

如果您必须重复执行此操作,您可以使用一个函数来执行解决方法:

def mpl_table_colors_fixed(ax, **kwargs):
    edges_tmp = kwargs["edges"]
    kwargs["edges"] = 'BTLR'
    
    tab1 = ax.table(**kwargs)
    for x in tab1.properties()['celld'].values():
        x.set(linewidth=0)

    kwargs["edges"] = edges_tmp
    tab2 = ax.table(**kwargs)
    
    return tab2

......然后这样称呼它:

table1 = mpl_table_colors_fixed(
    ax,
    cellText=sample_data,
    cellColours=sample_colors,
    cellLoc='center',
    loc='center',
    edges = 'B')

相关问题