在matplotlib中打印带有相应图例的文本条目(并具有格式化的可能性)

2024-09-28 22:02:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在matplotlib中用适当的图例绘制文本条目,也就是说,文本条目就像标记一样,应该与图例中的一些解释一起复制

我确定了三种可能的方法来实现这一点,但没有一种方法能提供我想要的控制:

  • plot与mathtext一起作为标记:对于图例很好,但是如何格式化文本本身(例如,避免粗体、斜体、选择字体系列等)
  • annotate:完全控制文本很好,但是我怎么能引用一个传说(马勒的出现和剧情完全一样)
  • text:与annotate相同

    import matplotlib.pyplot as plt
    
    myd = dict((k, v) for (k, v) in zip(('FOO', 'BLA', 'OOP'),
                                        ('Foofighters!', 'BlackPanther', 'Oops I did it again')))
    mycolors = ('r', 'b', 'g')
    
    fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(10,4), sharex=True, sharey=True)
    
    for i, (k,v) in enumerate(myd.items()):
    
        ax0.plot(i, i, marker='$%s$' % k, ms=20, lw=0, label = v,
                 color=mycolors[i])
        ax0.legend(loc=2)
    
        ax1.annotate(k, xy=(i, i), label=v, ha='center', va='center',
                     color=mycolors[i], fontweight='extra bold')
        ax1.legend(loc=2)
    
        ax2.text(i, i, k, label=v, ha='center', va='center',
                 color=mycolors[i], family='fantasy', rotation=15)
        ax2.legend(loc=2)
    
    fig.tight_layout()
    plt.show()
    

enter image description here


Tags: 文本matplotlib条目pltloclabelcolorcenter