Pyplot:曲线下的垂直梯度填充?

2024-05-19 13:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有办法用垂直梯度填充pyplot曲线下,就像在这个快速模型中:

image

我在StackOverflow上找到了这个技巧,如果我能弄清楚如何使颜色映射垂直,我不介意多边形:How to fill rainbow color under a curve in Python matplotlib


Tags: to模型技巧颜色多边形stackoverflowfill曲线
2条回答

有一个更接近问题草图的替代解决方案。这是亨利·巴特的博客上写的。 这将对每个补丁应用imshow,我已经复制了代码以防链接更改

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

也许有更好的方法,但这里有:

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

显示:

enter image description here

相关问题 更多 >