matplotlib绘图函数中是否可以为线条添加边框(轮廓)?

32

我尝试:

points = [...]
axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=10, 
color='black', markeredgewidth=2, markeredgecolor='green')
但是我只得到了一个黑色的轮廓。我怎样才能实现类似下面图片中的效果? 带有绿色边框的黑线
3个回答

84

如果您绘制一条线两次,它不会出现在图例中。使用patheffects确实更好。以下是两个简单的示例:

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

enter image description here


非常感谢您指出 path_effects。这甚至适用于 collections。像这样: 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')]) - Mikhail Lisakov
谢谢你分享这个例子,@Mattijn。我尝试给虚线添加边框,但无法插入间隔处。你知道有什么解决方法吗? - Stefano
太棒了!它甚至可以在文本上运行。 - Ted Tinker

10

只需使用不同的线条粗细绘制两次即可:

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

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接