在 Matplotlib 中创建带刻度的线条样式

Beginner

This tutorial is from open-source community. Access the source code

简介

在 Matplotlib 中,patheffects可用于改变路径的绘制方式。TickedStroke是一种patheffect,它以带刻度的样式绘制线条。本教程将指导你在 Matplotlib 中创建TickedStroke的步骤。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到笔记本标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会立即为你解决问题。

对路径应用带刻度的线条样式

在这一步中,我们将对路径应用带刻度的线条样式(TickedStroke)。

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.patheffects as patheffects

fig, ax = plt.subplots(figsize=(6, 6))
path = path.Path.unit_circle()
patch = patches.PathPatch(path, facecolor='none', lw=2, path_effects=[
    patheffects.withTickedStroke(angle=-90, spacing=10, length=1)])

ax.add_patch(patch)
ax.axis('equal')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)

plt.show()

这段代码将创建一个带有带刻度的线条样式路径效果的单位圆。

对线条应用带刻度的线条样式

在这一步中,我们将对线条应用带刻度的线条样式(TickedStroke)。

fig, ax = plt.subplots(figsize=(6, 6))
ax.plot([0, 1], [0, 1], label="Line",
        path_effects=[patheffects.withTickedStroke(spacing=7, angle=135)])

nx = 101
x = np.linspace(0.0, 1.0, nx)
y = 0.3*np.sin(x*8) + 0.4
ax.plot(x, y, label="Curve", path_effects=[patheffects.withTickedStroke()])

ax.legend()

plt.show()

这段代码将创建一条带有带刻度的线条样式路径效果的直线和一条曲线。

对等高线图应用带刻度的线条样式

在这一步中,我们将对等高线图应用带刻度的线条样式(TickedStroke)。

fig, ax = plt.subplots(figsize=(6, 6))

nx = 101
ny = 105

## 设置测量向量
xvec = np.linspace(0.001, 4.0, nx)
yvec = np.linspace(0.001, 4.0, ny)

## 设置测量矩阵。设计盘载荷和传动比。
x1, x2 = np.meshgrid(xvec, yvec)

## 计算一些要绘制的内容
obj = x1**2 + x2**2 - 2*x1 - 2*x2 + 2
g1 = -(3*x1 + x2 - 5.5)
g2 = -(x1 + 2*x2 - 4.5)
g3 = 0.8 + x1**-3 - x2

cntr = ax.contour(x1, x2, obj, [0.01, 0.1, 0.5, 1, 2, 4, 8, 16],
                  colors='black')
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)

cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
plt.setp(cg1.collections,
         path_effects=[patheffects.withTickedStroke(angle=135)])

cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
plt.setp(cg2.collections,
         path_effects=[patheffects.withTickedStroke(angle=60, length=2)])

cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
plt.setp(cg3.collections,
         path_effects=[patheffects.withTickedStroke(spacing=7)])

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)

plt.show()

这段代码将创建一个带有带刻度的线条样式路径效果的等高线图。

刻度的方向/侧边

在这一步中,我们将更改刻度的侧边。

fig, ax = plt.subplots(figsize=(6, 6))
line_x = line_y = [0, 1]
ax.plot(line_x, line_y, label="Line",
        path_effects=[patheffects.withTickedStroke(spacing=7, angle=135)])

ax.plot(line_x, line_y, label="Opposite side",
        path_effects=[patheffects.withTickedStroke(spacing=7, angle=-135)])

ax.legend()
plt.show()

这段代码将创建一条两侧都有刻度的线。

总结

本教程展示了如何在 Matplotlib 中创建带刻度的线条样式(TickedStroke)。通过遵循这些步骤,你可以将带刻度的线条样式应用于路径、线条和等高线图。你还可以调整刻度的方向/侧边。