【问题标题】:Is it possible to get color gradients under curve in matplotlib?是否可以在 matplotlib 中获得曲线下的颜色渐变?
【发布时间】:2015-06-02 00:42:46
【问题描述】:

我碰巧在page 上看到了一张漂亮的图表,如下所示:

matplotlib 中可以得到这样的颜色渐变吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    以前有一些类似问题的答案(例如https://stackoverflow.com/a/22081678/325565),但他们建议采用次优方法。

    之前的大多数答案都建议在pcolormesh 填充上绘制一个白色多边形。这并不理想,原因有两个:

    1. 坐标区的背景不能是透明的,因为上面有一个填充的多边形
    2. pcolormesh 的绘制速度相当慢,并且插值不平滑。

    这需要更多的工作,但有一种方法可以更快地绘制并提供更好的视觉效果:设置使用imshow 绘制的图像的剪辑路径。

    举个例子:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    from matplotlib.patches import Polygon
    np.random.seed(1977)
    
    def main():
        for _ in range(5):
            gradient_fill(*generate_data(100))
        plt.show()
    
    def generate_data(num):
        x = np.linspace(0, 100, num)
        y = np.random.normal(0, 1, num).cumsum()
        return x, y
    
    def gradient_fill(x, y, fill_color=None, ax=None, **kwargs):
        """
        Plot a line with a linear alpha gradient filled beneath it.
    
        Parameters
        ----------
        x, y : array-like
            The data values of the line.
        fill_color : a matplotlib color specifier (string, tuple) or None
            The color for the fill. If None, the color of the line will be used.
        ax : a matplotlib Axes instance
            The axes to plot on. If None, the current pyplot axes will be used.
        Additional arguments are passed on to matplotlib's ``plot`` function.
    
        Returns
        -------
        line : a Line2D instance
            The line plotted.
        im : an AxesImage instance
            The transparent gradient clipped to just the area beneath the curve.
        """
        if ax is None:
            ax = plt.gca()
    
        line, = ax.plot(x, y, **kwargs)
        if fill_color is None:
            fill_color = line.get_color()
    
        zorder = line.get_zorder()
        alpha = line.get_alpha()
        alpha = 1.0 if alpha is None else alpha
    
        z = np.empty((100, 1, 4), dtype=float)
        rgb = mcolors.colorConverter.to_rgb(fill_color)
        z[:,:,:3] = rgb
        z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]
    
        xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
        im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                       origin='lower', zorder=zorder)
    
        xy = np.column_stack([x, y])
        xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
        clip_path = Polygon(xy, facecolor='none', edgecolor='none', closed=True)
        ax.add_patch(clip_path)
        im.set_clip_path(clip_path)
    
        ax.autoscale(True)
        return line, im
    
    main()
    

    【讨论】:

    • 这真是太棒了!您是否看到了一种使渐变也跟随曲线的方法?即,不是z 的 alpha 值从 0 到 1(在坐标轴坐标中)均匀拉伸,而是让 z 从 0 拉伸到 y(在数据坐标中)?
    • 当保存为矢量格式时,需要设置plt.rcParams["image.composite_image"] = False,否则剪切不能正常工作。
    • 确实很棒。
    • 上面的代码应该独立运行吗?当我将它粘贴到我的 Python 控制台时,我无法执行它并得到一大堆错误。我得到的第一个错误在第 41 行,不太清楚为什么:line, = ax.plot(x, y, **kwargs) 这里是错误File "<stdin>", line 1 line, = ax.plot(x, y, **kwargs) IndentationError: unexpected indent
    • 如果我保存文件并执行它,它会起作用,我很想知道为什么当我将它复制粘贴到 python 控制台时它不起作用
    【解决方案2】:

    请注意Joe Kington 值得在这里获得最大的赞誉;我唯一的贡献是zfunc。 他的方法为许多渐变/模糊/投影打开了大门 效果。例如,要使线条的底面均匀模糊,您可以 可以使用 PIL 构建一个 alpha 层,该层靠近线为 1,靠近底部边缘为 0。

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    import matplotlib.patches as patches
    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFilter
    
    np.random.seed(1977)
    def demo_blur_underside():
        for _ in range(5):
            # gradient_fill(*generate_data(100), zfunc=None) # original
            gradient_fill(*generate_data(100), zfunc=zfunc)
        plt.show()
    
    def generate_data(num):
        x = np.linspace(0, 100, num)
        y = np.random.normal(0, 1, num).cumsum()
        return x, y
    
    def zfunc(x, y, fill_color='k', alpha=1.0):
        scale = 10
        x = (x*scale).astype(int)
        y = (y*scale).astype(int)
        xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    
        w, h = xmax-xmin, ymax-ymin
        z = np.empty((h, w, 4), dtype=float)
        rgb = mcolors.colorConverter.to_rgb(fill_color)
        z[:,:,:3] = rgb
    
        # Build a z-alpha array which is 1 near the line and 0 at the bottom.
        img = Image.new('L', (w, h), 0)  
        draw = ImageDraw.Draw(img)
        xy = (np.column_stack([x, y]))
        xy -= xmin, ymin
        # Draw a blurred line using PIL
        draw.line(map(tuple, xy.tolist()), fill=255, width=15)
        img = img.filter(ImageFilter.GaussianBlur(radius=100))
        # Convert the PIL image to an array
        zalpha = np.asarray(img).astype(float) 
        zalpha *= alpha/zalpha.max()
        # make the alphas melt to zero at the bottom
        n = zalpha.shape[0] // 4
        zalpha[:n] *= np.linspace(0, 1, n)[:, None]
        z[:,:,-1] = zalpha
        return z
    
    def gradient_fill(x, y, fill_color=None, ax=None, zfunc=None, **kwargs):
        if ax is None:
            ax = plt.gca()
    
        line, = ax.plot(x, y, **kwargs)
        if fill_color is None:
            fill_color = line.get_color()
    
        zorder = line.get_zorder()
        alpha = line.get_alpha()
        alpha = 1.0 if alpha is None else alpha
    
        if zfunc is None:
            h, w = 100, 1
            z = np.empty((h, w, 4), dtype=float)
            rgb = mcolors.colorConverter.to_rgb(fill_color)
            z[:,:,:3] = rgb
            z[:,:,-1] = np.linspace(0, alpha, h)[:,None]
        else:
            z = zfunc(x, y, fill_color=fill_color, alpha=alpha)
        xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
        im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                       origin='lower', zorder=zorder)
    
        xy = np.column_stack([x, y])
        xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
        clip_path = patches.Polygon(xy, facecolor='none', edgecolor='none', closed=True)
        ax.add_patch(clip_path)
        im.set_clip_path(clip_path)
        ax.autoscale(True)
        return line, im
    
    demo_blur_underside()
    

    产量

    【讨论】:

    • 不错!我打算添加一个纯粹的垂直移位,但我想我更喜欢你的高斯模糊。
    • scale在zfunc方法中有什么意义?
    • @Jared:zfunc 创建了一个小的(模糊的)PIL 图像。 PIL 图像的大小 (w, h) 取决于 xmax-xmin 和 ymax-ymin 的差异。如果这些差异太小,那么 PIL 图像的分辨率就会很低。如果分辨率太低,模糊看起来不会很平滑。所以我将x 和y 的值乘以scale,这样PIL 图像的尺寸就会更大。
    • @unutbu 我已尝试在此处复制您的解决方案,看起来不错,但收效甚微。我已经包含了一个完整的、可复制的示例(但诚然不是那么简洁......我正在努力减少它,但不能删除太多)here。你知道这个故障是从哪里来的吗?
    • 我很想解释一下这段代码的每一部分是做什么的。我明白了大致的想法,但有些细节不清楚。
    【解决方案3】:

    我已经尝试过:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    
    xData = range(100)
    yData = range(100)
    plt.plot(xData, yData)
    
    NbData = len(xData)
    MaxBL = [[MaxBL] * NbData for MaxBL in range(100)]
    Max = [np.asarray(MaxBL[x]) for x in range(100)]
    
    for x in range (50, 100):
      plt.fill_between(xData, Max[x], yData, where=yData >Max[x], facecolor='red', alpha=0.02)
    
    for x in range (0, 50):
      plt.fill_between(xData, yData, Max[x], where=yData <Max[x], facecolor='green', alpha=0.02)
    
    plt.fill_between([], [], [], facecolor='red', label="x > 50")
    plt.fill_between([], [], [], facecolor='green', label="x < 50")
    
    plt.legend(loc=4, fontsize=12)
    plt.show()
    fig.savefig('graph.png')
    

    .. 结果:

    当然,通过改变feel_between函数的范围,梯度可以降到0。

    【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2022-12-15
    • 2020-05-29
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2020-09-26
    相关资源
    最近更新 更多