Leo
Leo

Reputation: 43

How do I set the width of the rowLabels column on matplotlib?

It seems code below should set the width of the column containing the row labels. Yet it only sets the other columns.

I've also tried passing a colWidths argument but the result is the same.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')
colLabels = ['ColA', 'ColB', 'ColC', 'ColD', 'ColE']
rowLabels = ['Row1', 'Row2', 'Row3', 'Row4']
dados = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20],

]
table = ax.table(
    cellText=dados, loc='center', 
    colLabels=colLabels, 
    rowLabels=rowLabels,
    # `colWidths=[0.15, 0.15, 0.15, 0.15, 0.15, 0.15, ],` # <- same result
)
for cell in table.get_celld().values():
    cell.set_width(.15)
    print(cell.get_text().get_text()) # shows that the column is iterated through

plt.show()

Upvotes: 1

Views: 234

Answers (1)

Matt Pitkin
Matt Pitkin

Reputation: 6407

The column containing the "Row" titles tries to automatically set the width. To stop this happening you can reset table._autoColumns to an empty list, e.g.,:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')
colLabels = ['ColA', 'ColB', 'ColC', 'ColD', 'ColE']
rowLabels = ['Row1', 'Row2', 'Row3', 'Row4']
dados = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20],

]
table = ax.table(
    cellText=dados, loc='center', 
    colLabels=colLabels, 
    rowLabels=rowLabels,
    # `colWidths=[0.15, 0.15, 0.15, 0.15, 0.15, 0.15, ],` # <- same result
)

table._autoColumns = []  # empty the _autoColumns

for cell in table.get_celld().values():
    cell.set_width(.15)
    print(cell.get_text().get_text()) # shows that the column is iterated through

plt.show()

Upvotes: 3

Related Questions