2

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):

enter image description here

Does anyone know if this is possible?

Thanks.

1 Answer 1

6

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()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.