python - 在 yticks 位置绘制表格

标签 python matplotlib

我一直在尝试找到一种以表格形式显示 3 元素列表的方法。我真正关心的是绘制表格。我想为图中的每个 ylabel 绘制一个 1by3 表。

以下是我到目前为止所拥有的。如果我能让每个表实例都显示出来,我就会得到我想要的。现在出现了对表格的引用,我不知道为什么。如果您实际查看引用位置出现的左中位置,您可以看到一张 1×3 的表格。

是否可以使用 matplotlib 为每个 ylabel 生成一个新表?表信息与条形图中的每一行直接相关,因此重要的是我有一种排列它们的方式。

条形图中的行数是动态的,因此为整个图创建 1 个表格并尝试将行与相应的条形图动态对齐是一个难题。

    # initialize figure
    fig = plt.figure()
    gs = gridspec.GridSpec(1, 2, width_ratios=[2, 1])
    fig.set_size_inches(18.5, 10.5)
    ax = fig.add_subplot(gs[0])

    #excluded bar graph code

    # create ylabels
    for row in range(1,len(data)):
        ylabel = [str(data[row][0]),str(data[row][1]),str(data[row][2])]
        ylabels.append(ylabel)

    #attempting to put each ylabel in a 1by3 table to display
    pos = np.arange(0.5,10.5,0.5)
    axTables = [None] * len(ylabels)
    for x in range(0,len(ylabels)):
        axTables[x] = fig.add_subplot(gs[0])
        ylabels[x] = axTables[x].table(cellText=[ylabels[x]], loc='left')

locsy, labelsy = plt.yticks(pos,ylabels)

enter image description here

最佳答案

首先,yticks 将期望文本作为输入,它无法处理其他对象。其次, table 需要位于轴内。

因此,为了在刻度(标签)的位置获取表格,想法可以是在 y 刻度标签的位置创建一个轴。一种选择是使用mpl_toolkits.axes_grid1.inset_locator.inset_axes。现在的困难在于,该轴需要沿 y 轴定位在数据坐标中,并且在图形(或像素)中沿水平方向定位。为此,可以使用混合变换。 inset_axes 允许以绝对度量(以英寸为单位)或相对度量给出宽度和高度,这很方便,因为我们可以将轴的宽度设置为边界框的 100%,而高度仍然是某个绝对值(我们不希望轴高度取决于数据坐标!)。 下面的函数 ax_at_posy 创建这样的轴。

然后,表格将紧贴在轴内,以便所有列的宽度相同。人们仍然需要确保始终使用相同的字体大小。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.transforms as mtrans

# General helper function to create an axes at the position of a yticklabel
def ax_at_posy(y, ax=None, width=0.3, leftspace=0.08, height=0.2):
    ax = ax or plt.gca()
    trans = mtrans.blended_transform_factory(ax.figure.transFigure, ax.transData)
    axins = inset_axes(ax, "100%", height, 
                       bbox_to_anchor=(leftspace, y, width-leftspace, 0.05),
                       bbox_transform=trans, loc="center right", borderpad=0.8)
    axins.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
    axins.axis("off")
    return axins


fig, ax = plt.subplots()
fig.subplots_adjust(left=0.4)

ax.scatter(np.random.rand(30), np.random.randint(7, size=30), c=np.random.rand(30))

get_data = lambda i: "".join(np.random.choice(list("abcdefgxyzt0"), size=i+2))
data = np.vectorize(get_data)(np.random.randint(2,6,size=(7,3)))

for i, row in enumerate(data):
    axi = ax_at_posy(i, ax=ax, width=0.4)
    tab = axi.table(cellText=[list(row)], loc='center', bbox=(0,0,1,1))
    tab.auto_set_font_size(False)
    tab.set_fontsize(9)
    plt.setp(tab.get_celld().values(), linewidth=0.72)

plt.show()

enter image description here

关于python - 在 yticks 位置绘制表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557573/

相关文章:

python - 使用 print 语句时显示特殊字符

python - 如何在 3D 曲面图中绘制 x、y、z 的 numpy 数组?

python - 使用 matplotlib 和 Axes3D 标记绘制日期

python - HTTPX RESPX Pytest TypeError : Invalid type for url. 预期 str 或 httpx.URL,得到 <class 'tuple' >:

python - Pandas 数据框排除特定范围内的行

python - 在列表中查找值的索引

python - Django Daphne 大文件上传

python - matplotlib子图的怪异之处

python - 如果 x 条目满足条件 python,则绘制 x-y 数据

python - 在 matplotlib 中改变寄生虫轴的颜色