在中插入图像/对象pyplot.tab页

2024-04-25 21:07:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码

import matplotlib
import matplotlib.pyplot as plt
cell_text = [
                ['56', '85', '84', '52', '90', '102', '133'],
                ['93', '95', '63', '117', '126', '100', '91'],
                ['60', '30', '30', '11', '10', '1', '33']
            ]
cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
rows = ["test1","test2","test3"]
the_table = plt.table(cellText=cell_text,
                      cellLoc = 'center',
                      rowLabels=rows,
                      rowColours=None,
                      colLabels=cols,
                      loc='bottom')

有没有办法将图像或对象(如matplotlib.patches.Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none'))插入行标签文本旁边的表中?例如,我试过

rows = [matplotlib.patches.Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none'),"test2","test3"]

但这只是在细胞内显示为Rectangle(xy=(50,100),width=40,height=30,angle=0)。你知道吗

动机:我正在尝试创建一个https://matplotlib.org/3.1.1/gallery/misc/table_demo.html的可呈现形式,但是使用图例标记(小矩形)而不是用相应的条形图颜色来着色单元格。你知道吗


Tags: textimportmatplotlibtablecellpltrowscols
1条回答
网友
1楼 · 发布于 2024-04-25 21:07:15

不能将对象“插入”到matplotlib中的表单元格中。表格单元格是一个带有关联文本的矩形。你知道吗

虽然可以编写一个与某个对象相关联的自定义单元格,并在绘图时定位该对象,但这里似乎更容易的解决方案是在所需对象的形状中使用unicode字符。这样就不需要对表单元格等进行非常复杂的子类化

例如,您可以使用shapes = ["◼", "◀", "●"]作为散点图的标记,以及表格单元格中的text元素。你知道吗

import numpy as np
import matplotlib.pyplot as plt

cell_text = [
                ['56', '85', '84', '52', '90', '102', '133'],
                ['93', '95', '63', '117', '126', '100', '91'],
                ['60', '30', '30', '11', '10', '1', '33']
            ]
cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
rows = ["test1","test2","test3"]
shapes = ["◼", "◀", "●"]
colors = ["crimson", "indigo", "limegreen"]

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.3, left=0.15)
ax.tick_params(labelbottom=False, bottom=False)

for y, s, c in zip(cell_text, shapes, colors):
    ax.scatter(cols, np.array(y).astype(float), c=c, marker=f"${s}$")
ax.set_xlim(-0.5,len(cols)-0.5)

table = ax.table(cellText=cell_text,
                      cellLoc = 'center',
                      rowLabels=rows,
                      rowColours=None,
                      colLabels=cols,
                      loc='bottom')
height = table.get_celld()[0,0].get_height()

for i in range(len(rows)):
    cell = table.add_cell(i+1, -2, width=0.07, height=height, text=shapes[i], 
                          loc="center")
    cell.get_text().set_color(colors[i])

plt.show()

enter image description here

相关问题 更多 >

    热门问题