12

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 could not find anything useful in this.

Is there an easy way to achieve the centering?

papafe
  • 2,959
  • 4
  • 41
  • 72

4 Answers4

28

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

Sakhri Houssem
  • 975
  • 2
  • 16
  • 32
willo
  • 959
  • 5
  • 8
6

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

EDIT 10/24/2021: As of today the above approach doesn't seem to work. It is however easy to fix it using set_text_props method of Cell objects (don't know if it didn't exit back then or I was unaware of it). To test it just add the following lines before the plt.show() of the official table demo. In this case the 4th column is centered.

cells = the_table.properties()["celld"]
for i in range(0, 5):
     cells[i, 3].set_text_props(ha="center")
Sabian
  • 135
  • 2
  • 7
2

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')
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
-1

Below method worked for me to change alignment for all cells.

col=5
rows=6
for i in range(0,col):
    for j in range(1,rows):
        cells[j, i].set_text_props(ha="center")
Pert8S
  • 582
  • 3
  • 6
  • 21