Home > front end >  Adding a plot to a matplotlib table
Adding a plot to a matplotlib table

Time:11-23

I have the following table:

fig,ax = plt.subplots(1,1,figsize=(16,16))
ax.axis('off')
nrows= 6
ncols=3
table = ax.table(cellText=[['']*ncols]*nrows,loc='top', rowLoc='center',colLoc='center')


for j,text in zip(range(3),['Group','Chart','Comments']):
    table[(0,j)].get_text().set_text(text)


for i,text in zip(range(1,nrows),list('ABCDE')):
    table[(i,0)].get_text().set_text(text)



for i in range(nrows):
    for j in range(ncols):
        table[(i,j)].set_height(0.2)
        table[(i,j)]._loc = 'center'
        table[(i,j)].set_fontsize(16)

I am trying to add a line chart to the middle column (Chart) enter image description here

for this example, the line can be just a diagonal

plt.plot([0,1],[0,1])

any ideas?

CodePudding user response:

I agree with Stef's comment, this would probably be easier using GridSpec and subplots. But for the sake of documenting this workaround:

You could use an inset axis inside the existing Table's axis. You would just have to find the xy location of the cell in which you want to plot them and their width/height.

You could add this to your code:

plt.draw()
for r in range(1, nrows):
    x0, y0, w, h = (*table[r, 1].get_xy(), table[r, 1].get_width()*.8, table[r, 1].get_height()*.8)
    axpl = ax.inset_axes(bounds=(x0 0.2*w, y0 0.2*h, w, h))
    axpl.plot([0, 1], [0, 1])

I decreased the inset axis size to fit in the cell.

Not that I used plt.draw() before the call so that the table[i,j].xy get populated correctly.

enter image description here

  • Related