注意
前往結尾以下載完整的範例程式碼。
TickedStroke 路徑效果#
Matplotlib 的 patheffects
可用於在足夠低的層級改變路徑的繪製方式,以影響幾乎任何事物。
路徑效果指南詳細說明了路徑效果的使用方式。
此處說明的 TickedStroke
路徑效果會以刻度樣式繪製路徑。可以控制刻度的間距、長度和角度。
另請參閱具有刻度路徑效果的線條範例。
另請參閱最佳化解空間的等高線繪製範例。
import matplotlib.pyplot as plt
import numpy as np
將 TickedStroke 套用至路徑#
import matplotlib.patches as patches
from matplotlib.path import Path
import matplotlib.patheffects as patheffects
fig, ax = plt.subplots(figsize=(6, 6))
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 套用至等高線圖#
具有目標和約束的等高線圖。等高線產生的曲線來表示最佳化問題中的典型約束,應以零度和 180 度之間的角度繪製。
fig, ax = plt.subplots(figsize=(6, 6))
nx = 101
ny = 105
# Set up survey vectors
xvec = np.linspace(0.001, 4.0, nx)
yvec = np.linspace(0.001, 4.0, ny)
# Set up survey matrices. Design disk loading and gear ratio.
x1, x2 = np.meshgrid(xvec, yvec)
# Evaluate some stuff to plot
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')
cg1.set(path_effects=[patheffects.withTickedStroke(angle=135)])
cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
cg2.set(path_effects=[patheffects.withTickedStroke(angle=60, length=2)])
cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
cg3.set(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()

指令碼的總執行時間: (0 分鐘 2.250 秒)