直接在matplotlib图上绘制箭头

时间:2016-04-26 16:49:36

标签: python matplotlib plot

我创建了一个包含网格上多个子图的图。这些图有两个不同的参数,所以我希望它看起来像是在坐标系中订购的。

我设法使用matplotlib.lines.Line2D()直接在图上的子图旁边绘制线条。 但我宁愿用箭头而不是一条线来使它更清晰。 (我可以使用fig.text()添加特定的参数值。)

I'd like the blue lines to be arrows

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from itertools import product 

fig = plt.figure()
plotGrid = mpl.gridspec.GridSpec(2, 2)

x = np.linspace(0,10,10000)
y = [j* np.sin(x + i)  for i,j in product(range(2), range(1,3))]

for i in range(4):
    ax = plt.Subplot(fig, plotGrid[i])

    for sp in ax.spines.values():
        sp.set_visible(False)

    ax.plot(x,y[i], color = 'r')
    ax.set_xticks([])
    ax.set_yticks([])
    fig.add_subplot(ax)

all_axes = fig.get_axes()


#I would like these lines to be arrows  
blcorPosn = 0.08 #bottom corner position
l1 = mpl.lines.Line2D([blcorPosn,blcorPosn], [1, blcorPosn],
                      transform=fig.transFigure, fig)

l2 = mpl.lines.Line2D([blcorPosn, 1], [blcorPosn, blcorPosn],
                      transform=fig.transFigure, fig)

fig.lines.extend([l1, l2])

我不确定这是否可行。但是我现在花了一天时间才这样做,我到目前为止看到绘制箭头的唯一方法是将它们直接画在轴上,但就我所知,这对我来说不是一个选择。

这也是我在这里发表的第一篇文章,因此非常感谢您提出如何提问的建议。 感谢

1 个答案:

答案 0 :(得分:0)

您可以使用稍微修改的FancyArrow补丁调用来替换每个轴上的Line2D。主要区别在于原点和目标x,y坐标被原点x,yx,y距离取代。这些值也作为参数直接传递,而不是作为列表传递:

l1 = mpl.patches.FancyArrow(blcorPosn, blcorPosn, 1, 0,
                            transform=fig.transFigure, figure=fig)

l2 = mpl.patches.FancyArrow(blcorPosn, blcorPosn, 0, 1,
                            transform=fig.transFigure, figure=fig)

FancyArrow补丁接受一些其他参数,以允许您自定义箭头的外观,包括width(线宽),head_widthhead_length。< / p>

Figure with axis arrows