Reputation: 530
I have to plot a tabular chart in Python and save this table as a jpeg/png. Then using this image in the mail. The problem is I am getting white space on top and bottom of the chart. Code I used to achieve this:
nrows, ncols = len(df)+1, len(df.columns)
hcell, wcell = 0.5, 1.5
hpad, wpad = 0, 0
fig, ax = plt.subplots(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
ax.axis('off')
ax.axis('tight')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.table(cellText=df.values, colLabels=df.columns, loc='center')
fig.savefig('table1.png', bbox_inches='tight')
Output: Also, I want to give the heading to the top and left-side of the chart. 'Some text Here' is the heading and yellow line shows where I want another heading. Desired Output without extra white space on the top.
Upvotes: 1
Views: 3594
Reputation: 339062
An option is to specify the bounding box of the table as the one to be used when saving the figure.
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
colums = ['col1', 'col2']
rows = ['row1', 'row2']
values = [[0, 1], [1, 0]]
table = ax.table(cellText=values, colLabels=colums, rowLabels=rows, loc='center')
ax.axis('off')
fig.canvas.draw()
bbox = table.get_window_extent(fig.canvas.get_renderer())
bbox_inches = bbox.transformed(fig.dpi_scale_trans.inverted())
fig.savefig('plop.png', bbox_inches=bbox_inches)
plt.show()
In this case the outer lines are croped because the line extends to both sides of its position. One may still add a little bit of padding around the table. E.g. to have 5 pixels padding,
bbox = table.get_window_extent(fig.canvas.get_renderer())
bbox = bbox.from_extents(bbox.xmin-5, bbox.ymin-5, bbox.xmax+5, bbox.ymax+5)
bbox_inches = bbox.transformed(fig.dpi_scale_trans.inverted())
Upvotes: 3
Reputation: 3306
I don't think you can delete the white spaces above and below your table. Reading the documentation, you already have the tighest you will ever achieve.
bbox_inches : str or Bbox, optional
Bbox in inches. Only the given portion of the figure is saved. If ‘tight’, try to figure out the tight bbox of the figure. If None, use savefig.bbox
However, I have made a working example for your properly set rows and columns. Here is the code, following the image.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
colums = ['col1', 'col2']
rows = ['row1', 'row2']
values = [[0, 1], [1, 0]]
ax.table(cellText=values, colLabels=colums, rowLabels=rows, loc='center')
ax.axis('off')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
fig.savefig('plop.png', bbox_inches='tight')
I strongly advise you to adjust your axis / figure settings after your plot is entirely drawn.
Upvotes: 0