Home > Blockchain >  Print matplotlib title just above a table extract form a Pandas Data frame
Print matplotlib title just above a table extract form a Pandas Data frame

Time:06-28

I have a data frame that can change size depending on the input. I plot this data frame in the form of a table using matplotlib. Here's my code :

fig, ax = plt.subplots()
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

the_table = ax.table(cellText=df_to_plot.values, colLabels=df_to_plot.columns, loc='center')
the_table.auto_set_font_size(False)  # To have a correct display
the_table.set_fontsize(7)
ax.set_title(f"{title}\n", y=1, pad=10)
fig.tight_layout() # I tried with and without
fig.savefig(save_name, bbox_inches='tight') # save_name end with .pdf

My problem appears when i have a dataframe with many rows, the title overlaps the table. I tried to put y=1 to print the title a the top of the fig but it stills overlaps. I tried to set a pad but it doesn't change anything. I tried to use .thight_layout() to correct it but it throws a error : UserWarning: Tight layout not applied.

My table does not exceed the pdf file but there is no place at the top for the title.Result of the matplotlib plot with the title overlaping

I want the title to be just above my table, regardless of its size.

CodePudding user response:

Using the bbox parameter gives you best control over placing the enter image description here

  • Related