Home > other >  Matplotlib Pyplot table - how to vertically center text after using scale to make cells taller?
Matplotlib Pyplot table - how to vertically center text after using scale to make cells taller?

Time:07-04

Based on this enter image description here

Notice however that the cell text is closer to the top of the cell than the bottom. Is there a way to vertically center the text within cells with this method or any other method?

CodePudding user response:

I think the scale(1, 2) adjustment results obtained in the referenced responses have an impact. If you adjust manually, the scale is about (1,1.4). To set the scale and position the string, you need to readjust the height in the second answer. cellDict contains the index and cell object, so set the height of that cell.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

colLabels = ['col 0', 'col 1', 'col 2']
rowLabels = ['row 0', 'row 1', 'row 2']

tableData = [['123', '123', '123'],
             ['123', '123', '123'],
             ['123', '123', '123']]

ax.set_axis_off()
ax.title.set_text('Table Title')

myTable = ax.table(cellText=tableData, rowLabels=rowLabels, colLabels=colLabels,
                   cellLoc='center', rowLoc='center', loc='center')
myTable.auto_set_font_size(False)
myTable.set_fontsize(12)
myTable.scale(1, 2)

cellDict = myTable.get_celld()
for cell in cellDict:
    #print(cell)
    cellDict[cell].set_height(0.2)

plt.show()

enter image description here

  • Related