Matplotlib 表 - 为不同的列分配不同的文本对齐方式 [英] Matplotlib Table- Assign different text alignments to different columns
问题描述
我正在创建一个两列表,希望文本尽可能地接近.如何指定第一列右对齐,第二列左对齐?
I am creating a two column table and want the text to be as close as possible. How can I specify that the first column be right aligned and the second be left aligned?
我尝试通过将常规cellloc设置为一侧(cellloc设置文本对齐方式)
I've tried by setting the general cellloc to one side (cellloc sets the text alignment)
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
然后遍历第二列中的单元格以将它们设置为左对齐:
Then looping through cells in the second columns to set them to left align:
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
上面的这个循环没有效果,文本保持右对齐.
This loop immediately above has no effect, and the text remains right aligned.
我错过了什么吗?或者这是不可能的?
Am I missing something? Or is this not possible?
编辑
对我来说,一种解决方法是将数据分成两个不同的列表,每列一个.这产生了我正在寻找的结果,但我想知道是否有人知道另一种方式.
A workaround is for me to separate the data into two different lists, one for each column. This produces the results I'm looking for, but I'd like to know if anyone knows of another way.
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
属性决定的.
Instead of setting the alignment of the text itself, you need to set the position of the text inside the table cell. This is determined by the cell's ._loc
attribute.
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()
(The approach used here is similar to changing the cell padding as in this question: Matplotlib Text Alignment in Table)
这篇关于Matplotlib 表 - 为不同的列分配不同的文本对齐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!