python - 在图表下设置颜色图

标签 python graph matplotlib color-mapping

我知道这已被详细记录,但我正在努力在我的代码中实现它。

我想用颜色图为图表下方的区域添加阴影。是否可以有一种颜色,即从超过 30 的任何点开始的红色,以及直到该点的渐变?

我正在使用 fill_between 方法,但如果有更好的方法,我很乐意更改它。

def plot(sd_values):

    plt.figure()
    sd_values=np.array(sd_values)
    x=np.arange(len(sd_values))
    plt.plot(x,sd_values, linewidth=1)
    plt.fill_between(x,sd_values, cmap=plt.cm.jet)
    plt.show()

这是目前的结果。我试过 axvspan,但这没有 cmap 作为选项。为什么下图没有显示颜色图?

enter image description here

最佳答案

我不确定 cmap 参数是否应该是 fill_between 绘图命令的一部分。在您的情况下,可能想使用 fill() 命令 btw。

这些填充命令创建多边形或多边形集合。多边形集合可以采用 cmap,但使用 fill 时,无法提供应为其着色的数据。

(据我所知)肯定不可能的是用您希望的渐变填充单个多边形。

下一个最好的办法就是伪造它。您可以绘制阴影图像并根据创建的多边形裁剪它。

# create some sample data
x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x) * 120

fig, ax = plt.subplots()

# plot only the outline of the polygon, and capture the result
poly, = ax.fill(x, y, facecolor='none')

# get the extent of the axes
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()

# create a dummy image
img_data = np.arange(ymin,ymax,(ymax-ymin)/100.)
img_data = img_data.reshape(img_data.size,1)

# plot and clip the image
im = ax.imshow(img_data, aspect='auto', origin='lower', cmap=plt.cm.Reds_r, extent=[xmin,xmax,ymin,ymax], vmin=y.min(), vmax=30.)

im.set_clip_path(poly)

图像被赋予一个范围,基本上将其拉伸(stretch)到整个轴上。然后 clip_path 让它只显示在绘制 fill 多边形的地方。

enter image description here

关于python - 在图表下设置颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19132402/

相关文章:

python - python networkx 中的图模块化

Python 2D Array - 引用网格的特定部分

python - 从 SPARQL 查询结果中排除空白节点

excel - 加权趋势线

python - 更改图例中椭圆 handle 的形状

python - 第二个 y 刻度重复轴刻度

python - __length_hint__ 什么时候会不准确?

html - 具有笛卡尔坐标系的简单可缩放 SVG 图形

android - MPAndroidChart 有没有办法为不同的条设置不同的颜色?

python - 使用排序文件绘制 X 轴与原始文件中相应的 Y 值