【问题标题】:Can I give a border (outline) to a line in matplotlib plot function?我可以给 matplotlib 绘图函数中的线条添加边框(轮廓)吗?
【发布时间】:2016-03-03 10:23:28
【问题描述】:

我试试:

points = [...]
axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=10, 
color='black', markeredgewidth=2, markeredgecolor='green')

但我只是得到一个黑色轮廓。我怎样才能达到下图所示的效果?

【问题讨论】:

    标签: python plot matplotlib


    【解决方案1】:

    如果您将一条线绘制两次,则它不会出现在图例中。使用路径效果确实更好。下面是两个简单的例子:

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.patheffects as pe
    
    # setup data
    x = np.arange(0.0, 1.0, 0.01)
    y = np.sin(2*2*np.pi*t)
    
    # create line plot including an outline (stroke) using path_effects
    plt.plot(x, y, color='k', lw=2, path_effects=[pe.Stroke(linewidth=5, foreground='g'), pe.Normal()])
    # custom plot settings
    plt.grid(True)
    plt.ylim((-2, 2))
    plt.legend(['sine'])
    plt.show()
    

    或者如果你想添加线条阴影

    # create line plot including an simple line shadow using path_effects
    plt.plot(x, y, color='k', lw=2, path_effects=[pe.SimpleLineShadow(shadow_color='g'), pe.Normal()])
    # custom plot settings
    plt.grid(True)
    plt.ylim((-2, 2))
    plt.legend(['sine'])
    plt.show()
    

    【讨论】:

    • 感谢您指向 path_effects。这甚至适用于集合。像这样: t = ax.add_collection(lines) t.set_path_effects([path_effects.PathPatchEffect(offset=(1,-1), facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1, facecolor='black')])
    • 感谢@Mattijn 的示例。我试图为虚线添加边框,但它在间隙处不起作用。你知道解决方法吗?
    • 漂亮!它甚至适用于文本。
    【解决方案2】:

    只需绘制两次不同粗细的线:

    axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=10, 
    color='green')
    axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=5, 
    color='black')
    

    【讨论】:

      【解决方案3】:

      更一般的答案是使用路径效应。为任何使用路径渲染的艺术家提供简单的轮廓和阴影(以及其他内容)。
      matplotlib 文档(和示例)非常易于访问。

      http://matplotlib.org/users/patheffects_guide.html

      http://matplotlib.org/examples/pylab_examples/patheffect_demo.html

      【讨论】:

        猜你喜欢
        • 2017-04-15
        • 1970-01-01
        • 1970-01-01
        • 2021-05-27
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 2020-09-24
        • 1970-01-01
        相关资源
        最近更新 更多