Reputation: 23
I have a dataframe which I want to show as table on a PDF file through matplotlib.
My code looks like this (I bypass what I do before as the data is not relevant, I guess, for my question):
table = ax_table.table(cellText=str_df.values, rowLabels=str_df.index, cellLoc='center',
colColours=['gainsboro'] * len(table_col), colLabels=table_col, loc='center',
colWidths= [0.12]*(len(table_col)), cellColours = img.to_rgba(df_for_table.values))
My dataframe (str_df) index name is "Area" and I would like to show it throught a matplotlib table instead of have a blank space (circled in red):
Does anyone know if this is possible?
Thanks.
Upvotes: 2
Views: 4602
Reputation: 339480
You can add a cell at the respective location and use the dataframe.index.name
as its text.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(1,50, size=(8,4)), columns=list("ABCD"))
df.index.name = "Name"
fig, ax = plt.subplots()
table = ax.table(cellText=df.values, rowLabels=df.index, cellLoc='center',
colColours=['gainsboro'] * len(df), colLabels=df.columns, loc='center',
colWidths= [0.12]*(len(df.columns)))
w, h = table[0,1].get_width(), table[0,1].get_height()
table.add_cell(0, -1, w,h, text=df.index.name)
plt.show()
Upvotes: 6