Adding color bar to 1D heatmap

57 views Asked by At

I have found an excellent answer from Creating a 1D heat map from a line graph but I need a color reference/side bar to show what numerical values each color represents.

There is a comment asking this same question on that page, but that comment was never answered.

I have modified the answer's code to my needs, slightly:

# https://stackoverflow.com/questions/45841786/creating-a-1d-heat-map-from-a-line-graph
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
plt.rcParams["figure.figsize"] = 5,2

x = np.arange(0,99)
y = np.random.uniform(-10, 10, 99)

fig, (ax,ax2) = plt.subplots(nrows=2, sharex=True)

extent = [x[0]-(x[1]-x[0])/2., x[-1]+(x[1]-x[0])/2.,0,1]
ax.imshow(y[np.newaxis,:], cmap="gist_rainbow", aspect="auto", extent=extent)
ax.set_yticks([])
ax.set_xlim(extent[0], extent[1])

ax2.plot(x,y)

plt.tight_layout()
plt.show()

but I don't know how to add the color bar. ax.imshow doesn't have an option for this. ax doesn't have a method that seems to do this.

I'm using matplotlib 3.8.0 and python 3.10.12

How can I add a colorbar to reference the colors in the top plot to a numerical value?

0

There are 0 answers