Matplotlib图例Unicode标记

3

我正在尝试在matplotlib的图例列表中放置特定的Unicode标记条目。

我想要一个看起来像这样的符号:| ---|(一条连续的线,也许不是很高的管道),以便将此注释放在图例列表中:

ax.annotate('', xy=(0, 1), xytext=(5, 1), arrowprops={'arrowstyle':'|-|'})

我所尝试的是以下内容:

我尝试过以下方法:

ax.scatter([], [], c='red', marker="$|---|$", s=120, label='my marker')

这段代码可以运行,但每个字符之间的间距看起来有点不协调。我找到了这个Unicode字符,它看起来有点类似于我想要的样子。请问是否有更好的选择?我想要一个结合了长向左的图钉长向右的图钉的符号,但不确定是否存在这种符号。
如何将Unicode用作图例项?我尝试过:
ax.scatter([], [], c='red', marker=u"$\U0001D129$", s=120, label='my marker')

可能是在matplotlib图例中使用文本而不是标记的重复问题。 - Guangyang Li
我不清楚您是想在图例还是注释中使用Unicode符号? - ImportanceOfBeingErnest
我想把它放在图例中。注释已经用第一行代码创建了。使用第二行代码添加注释的图例条目。然而,marker="$|---|$"看起来并不像由arrowprops={'arrowstyle':'|-|'}创建的注释。 - user33236
2个回答

3

看起来使用Unicode符号只是将实际的注释箭头放在图例中的一种解决方法。可以通过使用自定义图例处理程序实现这一点。为此,可以子类化线条的图例处理程序并在其中放置注释箭头。然后调用它会像这样:

annotate = ax.annotate(..., label="marker")
ax.legend(handles = [annotate], 
          handler_map={type(annotate) : AnnotationHandler(5)})

这里的5是突变比例,表示箭头中垂直线的长度。

enter image description here

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

class AnnotationHandler(HandlerLine2D):
    def __init__(self,ms,*args,**kwargs):
        self.ms = ms
        HandlerLine2D.__init__(self,*args,**kwargs)
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize,
                       trans):
        xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
                                             width, height, fontsize)
        ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
        legline = FancyArrowPatch(posA=(xdata[0],ydata[0]),
                                  posB=(xdata[-1],ydata[-1]),
                                  mutation_scale=self.ms,
                                  **orig_handle.arrowprops)
        legline.set_transform(trans)
        return legline,



fig, ax = plt.subplots()
ax.axis([-1,6,0,3])
ax.plot([1.5,1.5], label="plot")
# create annotations in the axes
annotate = ax.annotate('', xy=(0, 1), xytext=(5, 1), 
                       arrowprops={'arrowstyle':'|-|'}, label="endline")
annotate2 = ax.annotate('', xy=(1, 2), xytext=(3, 2), 
                       arrowprops=dict(arrowstyle='->',color="crimson"), label="arrow")
# create legend for annotations
h, l = ax.get_legend_handles_labels()
ax.legend(handles = h +[annotate,annotate2], 
          handler_map={type(annotate) : AnnotationHandler(5)})

plt.show()

谢谢,这是一个适当的修复。 - user33236

0

我找到了一个还不错的解决方案。

ax.scatter([], [], c='red', marker=u'$\u22a2\!\u22a3$', s=150, label='my marker')

这里使用了右 tack (\u22a2) 和左 tack (\u22a3),以及负间距 (\!) 将两个字符连接成一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接