【问题标题】:Matplotlib Table- Assign different text alignments to different columnsMatplotlib 表 - 为不同的列分配不同的文本对齐方式
【发布时间】:2018-01-12 00:19:44
【问题描述】:

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

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

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

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

    【讨论】:

    • 我试过 .loc 并没有得到结果;没有意识到它必须是._loc。谢谢!
    • 这个绝妙的解决方案不适用于 Matplotlib 3.2.2。我不得不降级到版本 3.1.2。不确定发生了什么变化。
    【解决方案2】:

    另一种可能的解决方案是使用您的表的方法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()
    

    这将给出相同的结果。

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 2018-07-21
      • 2016-03-15
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多