Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding color bar to a table matplotlib

I have the following code for making a table plot in matplotlib.

fig = plt.figure(figsize=(15,8))
ax = fig.add_subplot(111, frameon=True, xticks = [], yticks = [])
tb = plt.table(cellText = cells[:30], rowLabels = range(30), colLabels = range(30), loc = 'center',cellColours = plt.cm.hot(normal(cells[:30])))
ax.add_table(tb)
plt.show()

plt is a pyplot object

I would like to add a color bar to this for the colormap I use.

I tried doing fig.colorbar() but that gives me a canvas error.

like image 283
gizgok Avatar asked Feb 26 '26 03:02

gizgok


1 Answers

You can create dummy image by imshow and hide it:

from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111, frameon=True, xticks = [], yticks = [])
cells = np.random.randint(0, 100, (10, 10))
img = plt.imshow(cells, cmap="hot")
plt.colorbar()
img.set_visible(False)
tb = plt.table(cellText = cells, 
    rowLabels = range(10), 
    colLabels = range(10), 
    loc = 'center',
    cellColours = img.to_rgba(cells))
ax.add_table(tb)
plt.show()

enter image description here

like image 85
HYRY Avatar answered Feb 27 '26 17:02

HYRY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!