如何在Python Matplotlib中的曲线下填充彩虹色 [英] How to fill rainbow color under a curve in Python matplotlib

查看:81
本文介绍了如何在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".

这篇关于如何在Python Matplotlib中的曲线下填充彩虹色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆