Centered text in matplotlib tables

后端 未结 3 1612
故里飘歌
故里飘歌 2021-01-17 23:02

I am trying to center the text inside a matplotlib table cell, while the default seems to be right aligned. I looked through the documentation of the Table object, but I cou

相关标签:
3条回答
  • 2021-01-17 23:49

    Try editing the sample here

    Adding

    cellLoc='center'
    

    To

    the_table = plt.table(cellText=cell_text,
                          rowLabels=rows,
                          rowColours=colors,
                          colLabels=columns,
                          loc='bottom')
    

    To get enter image description here

    0 讨论(0)
  • 2021-01-17 23:49

    Another answer which edits the cell's alignment individually, serves this case and a more general one where only arbitrary columns (but not all) are to be centered (or any specific cells to that case).

    Let's say you have a 5 rows - 3 columns table. If you want to edit only first column:

    the_table = plt.table(cellText=cell_text,
                          rowLabels=rows,
                          rowColours=colors,
                          colLabels=columns,
                          loc='bottom')
    
    cells = the_table.properties()["celld"]
    for i in range(0, 5):
        cells[i, 0]._loc = 'center'
    

    I was stuck with this until I took a look at table.py source

    0 讨论(0)
  • 2021-01-17 23:52

    According to documentation, there is this metthod in cell object :

    set_text_props(self, **kwargs)
    

    kwargs may refers to text methods/attribute, such this one:

    horizontalalignment or ha = [ 'center' | 'right' | 'left' ]
    

    So, what about :

    cell.set_text_props(ha='center')
    
    0 讨论(0)
提交回复
热议问题