Skip to main content
 首页 » 编程设计

python之Matplotlib 图例 unicode 标记

2024年09月07日7java哥

我试图在 matplotlib 的图例列表中放置一个特定的 unicode 标记条目。

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

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

我试过的是:

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

这行得通,但每个字符之间的间距看起来有点糟糕。我找到了 this看起来有点像我想要的 unicode 字符。任何人都知道哪个看起来更好?我想要 long left tack 的组合 和 long right tack ,但不知道是否存在。

如何使用 unicode 作为图例条目?我试过了:

ax.scatter([], [], c='red', marker=u"$\U0001D129$", s=120, label='my marker') 

请您参考如下方法:

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

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

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

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()