如何在Python Matplotlib中的曲线下填充彩虹色

问题描述:

我想在曲线下填充彩虹色.实际上函数 matplotlib.pyplot.fill_between 可以用单一颜色填充曲线下的区域.

I want to fill rainbow color under a curve. Actually the function matplotlib.pyplot.fill_between can fill area under a curve with a single color.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 100, 50) 
y = -(x-50)**2 + 2500
plt.plot(x,y)
plt.fill_between(x,y, color='green')
plt.show()

是否有一个旋钮可以将颜色调整为彩虹色?谢谢.

Is there a knob I can tweak the color to be rainbow? Thanks.

如果你想用一系列矩形填充",这很容易破解:

This is pretty easy to hack if you want "fill" with a series of rectangles:

import numpy as np
import pylab as plt

def rect(x,y,w,h,c):
    ax = plt.gca()
    polygon = plt.Rectangle((x,y),w,h,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)
        rect(x,0,dx,y,color)

# Test data    
X = np.linspace(0,10,100)
Y = .25*X**2 - X
rainbow_fill(X,Y)
plt.show()

您可以通过使矩形变小(即使用更多点)来平滑锯齿状的边缘.此外,您可以使用梯形(甚至内插多项式)来细化矩形".

You can smooth out the jagged edges by making the rectangles smaller (i.e. use more points). Additionally you could use a trapezoid (or even an interpolated polynomial) to refine the "rectangles".