简体   繁体   中英

How to show dataframe index name on a matplotlib table?

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.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM