如何在Matplotlib绘图中添加复杂箭头表示“跳跃”效果?
在Matplotlib中绘制“跳跃”箭头表示势阱间跃迁
要实现物体从右侧势阱跃入中心深势阱的箭头效果,你可以用Matplotlib的FancyArrowPatch自定义带路径的箭头,模拟翻越山丘的轨迹。以下是修改后的完整代码:
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import FancyArrowPatch fig, ax = plt.subplots(dpi=100) fig.patch.set_alpha(0.9) L = 2 def well(x, depth=10, centre=0, flatten=0.2): return -depth * np.exp(-0.5 * ((x-centre)/flatten)**2) wells = [-2*L, -1*L, 0, L, 2*L] wells_xs = [] for centre in wells: wells_xs.append(np.linspace(centre-0.5*L, centre+0.5*L, 100)) # 绘制势阱 for center, space in zip(wells, wells_xs): d = 8 if center == 0 else 1 flatten = 0.3 if center == 0 else 0.4 ax.plot(space, well(space, d, center, flatten), 'deepskyblue') # 定义跳跃箭头的关键坐标 # 起点:右侧势阱(x=2)的最低点 start_x = wells[3] start_y = well(start_x, depth=1, centre=start_x, flatten=0.4) # 终点:中心势阱(x=0)的最低点 end_x = wells[2] end_y = well(end_x, depth=8, centre=end_x, flatten=0.3) # 创建弧形跳跃箭头 arrow = FancyArrowPatch( posA=(start_x, start_y), posB=(end_x, end_y), connectionstyle=f'arc3,rad=-0.3', # rad控制弧线弯曲方向和幅度,负值向左弯 arrowstyle='->', color='darkred', linewidth=2, zorder=10 # 确保箭头在势阱图层上方 ) ax.add_patch(arrow) plt.show()
关键说明:
- 轨迹调整:
connectionstyle='arc3,rad=-0.3'中的rad参数可自定义:绝对值越大,弧线弯曲程度越高;负值让箭头向左弯曲,契合从右到左翻越山丘的方向。 - 层级控制:
zorder=10保证箭头不会被势阱曲线遮挡。 - 自定义路径:如果需要更贴合草图的折线式跳跃,可改用
Path类定义多段顶点,再传入FancyArrowPatch的path参数。
内容的提问来源于stack exchange,提问作者Woodenplank
相关产品推荐
相关产品推荐

