Matplotlib is hiring a Research Software Engineering Fellow! See discourse for details. Apply by January 3, 2020
定义对象在画布上遵循的路径。
Matplotlib patheffects 模块提供了将多个绘制阶段应用于任何可通过 Path .
可以应用路径效果的艺术家包括 Patch , Line2D , Collection 甚至 Text . 每个艺术家的路径效果可以通过 set_path_effects 方法 (set_path_effects ,这需要 AbstractPathEffect 实例。
最简单的路径效应是 Normal 效果,简单地画出没有任何效果的艺术家:
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
fig = plt.figure(figsize=(5, 1.5))
text = fig.text(0.5, 0.5, 'Hello path effects world!\nThis is the normal '
'path effect.\nPretty dull, huh?',
ha='center', va='center', size=20)
text.set_path_effects([path_effects.Normal()])
plt.show()
虽然绘图与没有任何路径效果的预期没有任何不同,但文本的绘图现在已更改为使用路径效果框架,从而为更有趣的示例打开了可能性。
更有趣的路径效果 Normal 是投影,我们可以应用于任何基于路径的艺术家。班级 SimplePatchShadow 和 SimpleLineShadow 通过在原始艺术家下面绘制填充的面片或线面片来精确地执行此操作:
import matplotlib.patheffects as path_effects
text = plt.text(0.5, 0.5, 'Hello path effects world!',
path_effects=[path_effects.withSimplePatchShadow()])
plt.plot([0, 3, 2, 5], linewidth=5, color='blue',
path_effects=[path_effects.SimpleLineShadow(),
path_effects.Normal()])
plt.show()
注意在这个例子中设置路径效果的两种方法。第一个使用 with* 类包含所需的功能,并自动跟随“正常”效果,而“正常”效果显式定义要绘制的两个路径效果。
让艺术家在视觉上脱颖而出的一个好方法是在实际艺术家的下方用粗体颜色画出一个轮廓。这个 Stroke 路径效应使得这项任务相对简单:
fig = plt.figure(figsize=(7, 1))
text = fig.text(0.5, 0.5, 'This text stands out because of\n'
'its black border.', color='white',
ha='center', va='center', size=30)
text.set_path_effects([path_effects.Stroke(linewidth=3, foreground='black'),
path_effects.Normal()])
plt.show()
需要注意的是,这种效果只起作用,因为我们已经绘制了两次文本路径;一次绘制了粗黑线,然后一次绘制了原始文本路径。
你可能已经注意到关键词 Stroke 和 SimplePatchShadow 和 SimpleLineShadow 不是常见的艺术家关键字(例如 facecolor 和 edgecolor 等等)。这是因为有了这些路径效应,我们在Matplotlib的较低级别上操作。事实上,接受的关键字是 matplotlib.backend_bases.GraphicsContextBase 实例,其设计目的是使创建新后端变得容易,而不是用于其用户界面。
如前所述,某些路径效果的操作级别低于大多数用户所使用的级别,这意味着设置诸如 facecolor 和 edgecolor 提出一个属性错误。幸运的是有一个通用的 PathPatchEffect 创建一个 PathPatch 用原始路径初始化。此效果的关键字与 PathPatch :
fig = plt.figure(figsize=(8, 1))
t = fig.text(0.02, 0.5, 'Hatch shadow', fontsize=75, weight=1000, va='center')
t.set_path_effects([path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx',
facecolor='gray'),
path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1,
facecolor='black')])
plt.show()