Search code examples
pythoncolorsmatplotlib

Shade the background of matplotlib based on array and colormap


I wonder if it is possible to shade the background of a typical matplotlib plot according to the data being plotted.

For simplicity, say we have:

x=arange(1,5,0.01)
y=sin(x)
plot(x,y)

Is it then possible to shade the background of the axes based on the y value?

The shading could be achieved by passing an array containing x and y to imshow such as:

imshow(array, cmap='hot')

although I want to have a line plot of x and y on top of this imshow figure.

Is this possible please?


Solution

  • Sure it's possible:

    x = arange(1,5,0.01)
    yarr = vstack((x,))
    y = sin(x)
    
    imshow(yarr, extent=(min(x),max(x), min(y),max(y)), cmap=cm.hot)
    plot(x, y, color='cornflowerblue',lw=4)
    

    The extent keyword matches the limits of the image to the plotted data.

    This will give you: this