Vinay
Vinay

Reputation: 1261

How to subplot a matplotlib table by using a custom plot function?

I am trying to create a function that takes axes of a subplot as a parameter and return a matplotlib table.

I was able to do this for barplots and lineplots using the code here. But trying the same for a table gives me an "error table() got multiple values for argument 'ax'"

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'var':['a','b','c','d'],'col1':[1,2,3,4],'col2':[1,4,9,16]})
df.set_index('var', inplace=True)


def plot_reg(df_x, ax=None):
    g = plt.table(cellText=df_x.values,
                  rowLabels=df_x.index,
                  colLabels=df_x.columns,loc='center', ax=ax)
    return g

fig, ax = plt.subplots(figsize=(8,5), ncols=2)
plot_reg(df, ax=ax[1])

I would like to get a similar result like the figure below.

fig, ax = plt.subplots(figsize=(8,5), ncols=2)
ax[1].table(cellText=df.values,rowLabels=df.index,colLabels=df.columns,loc='right')
# ax[1].axis('tight')
ax[1].axis('off')

enter image description here

Upvotes: 0

Views: 1865

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40737

I don't know if I understood your question, but you could write your function as:

def plot_reg(df_x, ax=None):
    ax = ax or plt.gca()  # either use the value passed as argument, or the current Axes
    g = ax.table(cellText=df_x.values,
                  rowLabels=df_x.index,
                  colLabels=df_x.columns,loc='center')
    return g

Upvotes: 1

Related Questions