I wish to format one column of a table but when iterating through the rows it appears the width of the column width changes after each iteration.
def p_create_table(self, events, dates, rows, columns, portfolio):
"""
:param events: Dict - {Date:Event} where Event is a String identifying
what event happened
:param dates: List - Dates of events
:param rows: Int - number of Dates (rows) to create for the table
:param columns: List - Column headers
:param portfolio: Dataframe - Portfolio with calculated totals and returns
:return:
"""
cell_text = self.p_create_cell_text(events, dates, portfolio)
cell_text.pop(0)
row_labels = self.p_create_row_labels(rows)
row_labels.pop(len(row_labels) - 1)
colors = self.p_set_table_colors(row_labels)
table = plt.table(cellText=cell_text, cellColours=colors[0],
rowColours=colors[1], rowLabels=row_labels,
colColours=colors[2], colLabels=columns,
bbox=[0.0, -1.3, 1.0, 1.0], cellLoc='center')
table.auto_set_font_size(False)
table.set_fontsize(9)
table.scale(2, 2)
cell_dict = table.get_celld()
for i in range(13):
cell_dict[(i,1)].set_width(0.3)
Below is an image of the table BEFORE the resizing. The snapshot was taken after line table.set_fontsize(9)
was executed. I would like to re-size the second column Event
.
Unfortunately, after ever iteration of:
for i in range(13):
cell_dict[(i,1)].set_width(0.3)
it looks like the cell width increases, resulting in something like this:
Any suggestions on why this could be happening, or an alternative solution to adjusting the width would be much appreciated!
Change column widthTo change the width to a specific measurement, click a cell in the column that you want to resize. On the Layout tab, in the Cell Size group, click in the Table Column Width box, and then specify the options you want.
BboxTransformTo is a transformation that linearly transforms points from the unit bounding box to a given Bbox. In your case, the transform itself is based upon a TransformedBBox which again has a Bbox upon which it is based and a transform - for this nested instance an Affine2D transform.
Setting the Column Width Set the width of a column by calling the Cells collection's setColumnWidth method. The setColumnWidth method takes the following parameters: Column index, the index of the column that you're changing the width of.
In addition to @jma answer, I found the table method .auto_set_column_width(col=<list of col indices>)
to be very helpful, especially in conjunction with .auto_set_font_size(False)
. Example use below:
from matplotlib import pyplot as plt
import pandas as pd
# Create some example data
data = [{"Movie": "Happy Gilmore", "Lead Actor": "Adam Sandler" , "Year": "1996",
"Plot": "An ice hockey star takes up golfing.",
"Quotes": "\"Just give it a little tappy. Tap tap taparoo.\""}]
dff = pd.DataFrame(data)
fig, ax = plt.subplots(3,1, figsize=(10,4))
tab0 = ax[0].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[0].set_title("Default")
tab1 = ax[1].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[1].set_title("Font AutoSize off")
tab2 = ax[2].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[2].set_title("Column Width Auto Set, Font AutoSize off")
[a.axis("off") for a in ax]
[t.auto_set_font_size(False) for t in [tab1, tab2]]
[t.set_fontsize(8) for t in [tab1, tab2]]
tab2.auto_set_column_width(col=list(range(len(dff.columns)))) # Provide integer list of columns to adjust
plt.show()
To set the width of the columns, use colWidths within the table function. It accepts a list of widths for each column--they can all be the same or different.
table = plt.table(cellText=cell_text, cellColours=colors[0],
rowColours=colors[1], rowLabels=row_labels,
colColours=colors[2], colLabels=columns,
colWidths=[0.3 for x in columns],
bbox=[0.0, -1.3, 1.0, 1.0], cellLoc='center')
Try my version of plot_table
data = [{"Movie": "Happy Gilmore", "Lead Actor": "Adam Sandler" , "Year": "1996",
"Plot": "An ice hockey star takes up golfing.",
"Quotes": "\"Just give it a little tappy. Tap tap taparoo.\""}]
df = pd.DataFrame(data)
data = np.vstack((df.columns.values, df.values.astype(str)))
plot_table(data);
Click here to get plot_table
source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With