gpt4 book ai didi

python - Matplotlib 表 - 为不同的列分配不同的文本对齐方式

转载 作者:太空狗 更新时间:2023-10-30 01:04:56 29 4
gpt4 key购买 nike

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

我试过将通用 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

然后遍历第二列中的单元格以将它们设置为左对齐:

for key, cell in tb.get_celld().items():
if key[1] == 1: # if the y value is equal to 1, meaning the second column
cell._text.set_horizontalalignment('left') # then change the alignment

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

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

编辑

我的解决方法是将数据分成两个不同的列表,每列一个。这会产生我正在寻找的结果,但我想知道是否有人知道另一种方法。

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)

最佳答案

您不需要设置文本本身的对齐方式,而是需要设置文本在表格单元格内的位置。这由单元格的 ._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

一些完整的例子:

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

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

set_align_for_column(tb, col=0, align="right")
set_align_for_column(tb, col=1, align="left")

plt.show()

enter image description here

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

关于python - Matplotlib 表 - 为不同的列分配不同的文本对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48210749/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com