我有以下代码
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,但要使用图例标记(小矩形),而不是用相应的条形颜色为单元格着色。
答案 0 :(得分:1)
您不能将对象“插入”到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()