这是使用梯形而不是矩形的已接受答案的修改解决方案。
import numpy as np
import pylab as plt
# a solution that uses rectangles
def rect(x,y,w,h,c):
ax = plt.gca()
polygon = plt.Rectangle((x,y),w,h,color=c)
ax.add_patch(polygon)
# a solution that uses trapezoids
def polygon(x1,y1,x2,y2,c):
ax = plt.gca()
polygon = plt.Polygon( [ (x1,y1), (x2,y2), (x2,0), (x1,0) ], color=c )
ax.add_patch(polygon)
def rainbow_fill(X,Y, cmap=plt.get_cmap("jet")):
plt.plot(X,Y,lw=0) # Plot so the axes scale correctly
dx = X[1]-X[0]
N = float(X.size)
for n, (x,y) in enumerate(zip(X,Y)):
color = cmap(n/N)
# uncomment to use rectangles
# rect(x,0,dx,y,color)
# uncomment to use trapezoids
if n+1 == N: continue
polygon(x,y,X[n+1],Y[n+1],color)
# Test data
X = np.linspace(0,10,100)
Y = .25*X**2 - X
rainbow_fill(X,Y)
plt.show()