Matplotlib表格为不同的列指定不同的文本对齐方式

2024-06-28 20:54:52 发布

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

我正在创建一个两列表,希望文本尽可能接近。如何指定第一列右对齐,第二列左对齐?在

我试过将常规cellloc设置为一侧(cellloc设置文本对齐方式)

from matplotlib import pyplot as plt

data = [['x','x'] for x in range(10)]
bbox = [0,0,1,1]

tb = plt.table(cellText = data, cellLoc='right', bbox = bbox)
plt.axis('off') # get rid of chart axis to only show table

然后循环第二列中的单元格,将其设置为左对齐:

^{pr2}$

上面的循环没有效果,文本保持右对齐。在

我错过什么了吗?或者这是不可能的吗?在

编辑

解决方法是将数据分为两个不同的列表,每列一个。这产生了我想要的结果,但我想知道是否有人知道其他方法。在

data_col1 = [xy[0] for xy in data]
data_col2 = [xy[1] for xy in data] 

tb = plt.table(cellText = data_col2, rowLabels=data_col1, cellLoc='left', rowLoc='right', bbox = bbox)

Tags: in文本right列表fordatatableplt
2条回答

您不需要设置文本本身的对齐方式,而是需要设置文本在表格单元格中的位置。这由单元格的._loc属性决定。在

def set_align_for_column(table, col, align="left"):
    cells = [key for key in table._cells if key[1] == col]
    for cell in cells:
        table._cells[cell]._loc = align

一些完整的例子:

^{pr2}$

enter image description here

(这里使用的方法类似于在这个问题中更改单元格填充:Matplotlib Text Alignment in Table

另一个可能的解决方案是使用表的get_celld()方法,该方法返回matplotlib.table.CustomCell对象的字典,然后可以循环使用并更改,方法与@ImportanceOfBeingErnest的答案类似:

from matplotlib import pyplot as plt

data = [['x','x'] for x in range(10)]
bbox = [0,0,1,1]

tb = plt.table(cellText = data, cellLoc='right', bbox = bbox)
plt.axis('off')

cells = tb.get_celld()

for i in range(0, len(data)):
    cells[i, 1]._loc = 'left'   # 0 is first column, 1 is second column

plt.show()

结果是一样的。在

相关问题 更多 >