我试图在matplotlib中添加一个复杂的箭头形状来表示"跳转"."(见草图)

Rough sketch of what I want the plot to look like

生成"井"的代码足够简单,这里供参考.

import matplotlib.pyplot as plt
import numpy as np

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')
plt.show()

我试图表明一个 idea ,即某个东西从右边的"坑"跳到深井,越过"小山"."所以直接从A指向B的箭头看起来不对. [3][2][3][2][3][2][3][2][3] X轴)

推荐答案

TL;DR

您可以使用matplotlib.patches.FancyArrowPatch在图形上绘制箭头.

Answer

matplotlib.patches中的FancyArrowPatch类允许您使用ax.add_patch(arrow)创建一个自定义箭头以添加到图形中. Select 正确的选项来获得您想要的确切箭头形状可能有点麻烦,但这段代码应该提供一个很好的起点.您可以调整起点/终点、曲率,甚至连接样式本身,以更改箭头的路径.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import FancyArrowPatch


def well(x, depth=10, centre=0, flatten=0.2):
    return -depth * np.exp(-0.5 * ((x-centre)/flatten)**2)


def get_arrow(start_point, end_point, line_width=2.0, color="red", curvature=1.0, mutation_scale=20):
    arrow_style = f'->'
    connection_style = f'arc3, rad={curvature}'
    arrow = FancyArrowPatch(start_point, end_point, connectionstyle=connection_style, arrowstyle=arrow_style, color=color, linewidth=line_width, mutation_scale=mutation_scale)
    return arrow


fig, ax = plt.subplots(dpi=100)
fig.patch.set_alpha(0.9)
L = 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')

start_point = (wells[3], 0)
end_point = (wells[2], -2)
arrow = get_arrow(start_point, end_point)

ax.add_patch(arrow)
plt.show()

A figure with a curved red arrow drawn on.

Python相关问答推荐

如何比较numPy数组中的两个图像以获取它们不同的像素

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

处理(潜在)不断增长的任务队列的并行/并行方法

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

如何找到满足各组口罩条件的第一行?

NP.round解算数据后NP.unique

将输入聚合到统一词典中

为一个组的每个子组绘制,

索引到 torch 张量,沿轴具有可变长度索引

不能使用Gekko方程'

用砂箱开发Web统计分析

如何在Python中获取`Genericums`超级类型?

名为__main__. py的Python模块在导入时不运行'

lityter不让我输入左边的方括号,'

从列表中获取n个元素,其中list [i][0]== value''

(Python/Pandas)基于列中非缺失值的子集DataFrame

jsonschema日期格式

如何使用pytest在traceback中找到特定的异常

Polars时间戳同步延迟计算

有什么方法可以在不对多索引DataFrame的列进行排序的情况下避免词法排序警告吗?