【问题标题】:Pyplot: vertical gradient fill under curve?Pyplot:曲线下的垂直渐变填充?
【发布时间】:2014-02-27 21:56:28
【问题描述】:

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

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

【问题讨论】:

    标签: python matplotlib gradient


    【解决方案1】:

    可能有更好的方法,但这里是:

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

    演出:

    【讨论】:

    • 这是非常好的跳出框框的想法,有渐变背景和白色填充。我不会很快想到这一点。
    • 而不是plt.contourf 我会使用plt.imshow 进行渐变填充。见my answer to this other question
    【解决方案2】:

    有一个更接近问题中草图的替代解决方案。它在 Henry Barthes 的博客 http://pradhanphy.blogspot.com/2014/06/filling-between-curves-with-color.html 上给出。 这会将 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()
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多