0

I have searched stack overflow extensively for a solution to my problem and have had no luck finding an answer. I am trying to save a matplotlib table as a png image with no whitespace background in the saved table image. the png image of the table is to be copied into another document, so having whitespace around the table image creates excess space between the image and the text that will be in the receiving document.

In savefig(), setting transparency=False is not my solution because I am not looking to not be able to see the background, I can't have the background there at all whether visible or invisible. I have tried bbox_inches="tight", pad_inches=0 in savefig(). I copied a solution (see function set_size() in my code) from a stack overflow question I found that is supposed to set the size of the axes object = size of the figure object, which i thought would have worked because I thought the whitespace was the difference in size between the figure and the table. If I'm using the set_size() correctly then that did not work either. When i drag and drop the png image of the table in paint.net, the excess whitespace is shown by the gray and white checkered pattern. I would be extremely grateful for a solution that gets rid of that checkered area. thank you

Code:

fig, ax = plt.subplots()
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
table = ax.table(cellText=quotes_df.values, colLabels=quotes_df.columns, cellLoc='center', loc='center')
for key, cell in table.get_celld().items():
    cell.set_edgecolor('white')
    cell.set_fontsize(12)

for num in range(0, 6):
    table.get_celld()[(0, num)].get_text().set_color("blue")
for num in range(0, 5):
    table.get_celld()[(0, num)].get_text().set_fontweight("bold")
    table.get_celld()[(0, num)].get_text().set_fontvariant("small-caps")
for num in range(1, 4):
    table.get_celld()[(num, 5)].get_text().set_color("blue")

def set_size(w, h, ax=None):
    """ w, h: width, height in inches """
    if not ax:
        ax = plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w) / (r - l)
    figh = float(h) / (t - b)
    ax.figure.set_size_inches(figw, figh)

set_size(12, 4)
plt.margins(x=0, y=0)
plt.savefig(save_path + save_name, dpi='figure', bbox_inches='tight', pad_inches=0)`
Matt
  • 1
  • 1
    Does this answer your question? [How to save figure in matplotlib ajusted to the object size?](https://stackoverflow.com/questions/74267842/how-to-save-figure-in-matplotlib-ajusted-to-the-object-size) – Joao_PS Nov 02 '22 at 18:28
  • that did not work Joao. thanks though – Matt Nov 02 '22 at 18:51

0 Answers0