11

I'm wondering if there's a way to fill under a pyplot curve with a vertical gradient, like in this quick mockup:

image

I found this hack on StackOverflow, and I don't mind the polygons if I could figure out how to make the color map vertical: How to fill rainbow color under a curve in Python matplotlib

Community
  • 1
  • 1
prooffreader
  • 2,333
  • 4
  • 21
  • 32

2 Answers2

13

There may be a better way, but here goes:

from matplotlib import pyplot as plt

x = range(10)
y = range(10)
z = [[z] * 10 for z in range(10)]
num_bars = 100  # more bars = smoother gradient

plt.contourf(x, y, z, num_bars)

background_color = 'w'
plt.fill_between(x, y, y2=max(y), color=background_color)

plt.show()

Shows:

enter image description here

mdscruggs
  • 1,182
  • 7
  • 15
  • 1
    That's pretty good thinking outside the box, having a gradient background and a white fill over it. It would not have occurred to me any time soon. – prooffreader Feb 27 '14 at 23:32
  • instead of `plt.contourf` I would use `plt.imshow` for the gradient fill. See [my answer to this other question](http://stackoverflow.com/a/42971319/4375377). – Mr Tsjolder from codidact Mar 23 '17 at 09:05
7

There is an alternative solution closer to the sketch in the question. It's given on Henry Barthes' blog http://pradhanphy.blogspot.com/2014/06/filling-between-curves-with-color.html. This applies an imshow to each of the patches, I've copied the code in case the link changes,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch

xx=np.arange(0,10,0.01)
yy=xx*np.exp(-xx)

path = Path(np.array([xx,yy]).transpose())
patch = PathPatch(path, facecolor='none')
plt.gca().add_patch(patch)

im = plt.imshow(xx.reshape(yy.size,1),   
                cmap=plt.cm.Reds,
                interpolation="bicubic",
                origin='lower',
                extent=[0,10,-0.0,0.40],
                aspect="auto",
                clip_path=patch, 
                clip_on=True)
plt.show()
arturomp
  • 28,790
  • 10
  • 43
  • 72
Ed Smith
  • 12,716
  • 2
  • 43
  • 55