0

I want to print the row of a dataframe below a plot. Here is my current code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

np.random.seed(1234)
df = pd.DataFrame(
    {'px_last': 100 + np.random.randn(1000).cumsum()},
    index=pd.date_range('2010-01-01', periods=1000, freq='B'),
)

fig, ax = plt.subplots(2,1)

# ax[0].plot(x,y,"k.")
# df.loc[idx, 'px_last'].plot(ax=ax, color=color, label='')
ax[0].plot(df.index, df['px_last'])
#url = 'https://raw.githubusercontent.com/kornelski/pngquant/master/test/img/test.png'
url = 'df_row1.png'
im = plt.imread(url)
implot = ax[1].imshow(im)

Right now, I save the first row of the dataframe as an image and plot it as a subplot for my main image. Is there an easier way to do this? I tried using dataframe_image as explained here but it only saves the image, I'm unable to find a way to plot it dynamically as a subplot.

Here is my expected output

enter image description here

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
user42
  • 871
  • 1
  • 10
  • 28

1 Answers1

1

After some research, it seems that I can achieve this by using the table function of mpl. I don't know if it is possible to optimize the data frame you want to show, because it is difficult to control the details of the table function. I have modified your code based on this answer and this answer.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from pandas.plotting import table

np.random.seed(1234)
df = pd.DataFrame(
    {'px_last': 100 + np.random.randn(1000).cumsum()},
    index=pd.date_range('2010-01-01', periods=1000, freq='B'),
)

fig, ax = plt.subplots(2,1)

ax[0].plot(df.index, df['px_last'])
tbl = table(ax[1], df.loc[[df.index[0]],:], loc='center', colWidths=[0.3 for x in df.columns])
# tbl.auto_set_column_width(col=list(range(len(df.columns))))

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32