Centered text in matplotlib tables

I'm trying to center 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 couldn't find anything useful about that.

Is there an easy way to achieve centering?

+3


source to share


3 answers


Try to edit the sample here

Adding

cellLoc='center'

      



To

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

To obtain enter image description here

+9


source


According to the documentation, this object has a metto object:

set_text_props(self, **kwargs)

      

kwargs can refer to text methods / attribute like:



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

      

So how about:

cell.set_text_props(ha='center')

      

0


source


Another answer, which edits cell alignment individually, serves this case and is more general, where only arbitrary columns (but not all) need to be centered (or any specific cells in that case).

Let's say you have a table with 5 rows - 3 columns. If you only want to edit the 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 on this until I looked at the table.py

source

0


source







All Articles