我正在尝试为每个单元格添加底部边框。
我试过这段代码,但它重置了表的颜色: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
1条答案
按热度按时间os8fio9y1#
我将
pandas.DataFrame
替换为包含任意数据的numpy.array
。matplotlib在多个版本中似乎有一个bug(我测试了v3.5.1和v3.7.2)。实际问题不是在彩色单元格上添加边框,而是当你没有在所有四个侧面使用单元格边框时,正确渲染单元格颜色。
下面是github上的相应讨论:https://github.com/matplotlib/matplotlib/issues/20100
您可以通过两次绘制同一个表来创建解决方法:
edges = 'BTLR'
以及线宽设置为零edges
值范例:
如果您必须重复执行此操作,您可以使用一个函数来执行解决方法:
......然后这样称呼它: