Reputation: 71
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.
I want the title to be just above my table, regardless of its size.
Upvotes: 1
Views: 879
Reputation: 30609
Using the bbox
parameter gives you best control over placing the table:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 1000, size=(88,7)))
fig, ax = plt.subplots(figsize=(210/25.4, 297/25.4), layout='constrained')
fig.suptitle('The Title')
ax.axis('off')
table = ax.table(cellText=df.values, colLabels=df.columns, bbox=[0,0,1,1])
table.set_fontsize(7)
fig.savefig('table.png', bbox_inches='tight')
Upvotes: 1