如何在matplotlib图例中添加字符串作为艺术家? [英] How to add a string as the artist in matplotlib legend?
问题描述
我正在尝试在python图形中创建图例,其中艺术家是一个字符串(单个字母),然后对其进行标记.例如,我想要下图的图例:
I am trying to create a legend in a python figure where the artist is a string (a single letter) which is then labelled. For example I would like a legend for the following figure:
import numpy as np
import matplotlib.pyplot as plt
import string
N = 7
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
for i,j in enumerate(zip(x,y)):
plt.annotate(list(string.ascii_uppercase)[i],xy=j)
plt.show()
图例如下:
A-型号名称A
B-型号B
C-型号C
D-型号D
etc.etc.
我不知道该怎么做,就是将"A","B",....作为图例文本的艺术家.我可以看到您将如何使用线路或补丁,或类似的东西.但是总的来说,有没有办法使用字符串作为艺术家而不是线条?
What I can't work out how to do is place 'A', 'B', .... as the artist for the legend text. I can see how you would use a line or Patch, or something similar. But in general is there a way to use a string as the artist instead of, say, a line?
推荐答案
我认为文本没有图例处理程序(请参见可用列表的清单自定义图例处理程序.在这里,我将在上面的链接上修改示例:
I don't think there's a legend handler for text (see the list of available ones here). But you can implement your own custom legend handler. Here I'll just modify the example at the above link:
import matplotlib.pyplot as plt
import matplotlib.text as mpl_text
class AnyObject(object):
def __init__(self, text, color):
self.my_text = text
self.my_color = color
class AnyObjectHandler(object):
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
print orig_handle
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
patch = mpl_text.Text(x=0, y=0, text=orig_handle.my_text, color=orig_handle.my_color, verticalalignment=u'baseline',
horizontalalignment=u'left', multialignment=None,
fontproperties=None, rotation=45, linespacing=None,
rotation_mode=None)
handlebox.add_artist(patch)
return patch
obj_0 = AnyObject("A", "purple")
obj_1 = AnyObject("B", "green")
plt.legend([obj_0, obj_1], ['Model Name A', 'Model Name B'],
handler_map={obj_0:AnyObjectHandler(), obj_1:AnyObjectHandler()})
plt.show()
这篇关于如何在matplotlib图例中添加字符串作为艺术家?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!