How to fill rainbow color under a curve in Python matplotlib

后端 未结 3 1496
庸人自扰
庸人自扰 2020-12-11 04:06

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 mat         


        
3条回答
  •  猫巷女王i
    2020-12-11 04:44

    Here is a modified solution of the accepted answer that uses trapezoids instead of rectangles.

    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()
    

提交回复
热议问题