想要在matplotlib图例上绘制不同大小/颜色的椭圆

时间:2019-10-07 17:42:14

标签: python matplotlib legend

我有一个情节,其中包含各种大小/颜色不同的椭圆,并希望为其创建一个“一般”图例,例如“大红色椭圆表示这个,小蓝色椭圆表示那个”等。

我在这里遵循了HandlerPatch示例,这使我获得了75%的收益。 https://matplotlib.org/3.1.1/tutorials/intermediate/legend_guide.html

使用上面的示例,我可以在图例中获得椭圆形状,并且可以自定义每个椭圆的颜色(通过为每个mpatches.Circle对象指定一个color参数)。这是其中的75%...但是它们的高度/宽度都相同,我不知道该如何控制,因为mpatches.Circle对象没有width参数,并且height / width是“硬编码的” ”添加到HandlerEllipse类的create_artists函数中。我可能非常接近,但完全被卡住了!任何帮助,不胜感激。

编辑

因此,由于托马斯·朗(Thomas Lang)建议查看此链接(https://intoli.com/blog/resizing-matplotlib-legend-markers/),我的工作是做类似的事情。在图例上绘制椭圆,然后遍历它们并更改其属性。参见下面的代码:

'''python

#exact same class as matplotlib example:
class HandlerEllipse(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
        p = mpatches.Ellipse(xy=center, width=width + xdescent,
                             height=height + ydescent)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]

cmap = cm.get_cmap(name='Spectral_r', lut=None)
#plotting a test case "two entry legend", tring to get two differently sized, differently colored ellipses    
c = [mpatches.Circle((),color=cmap(0.1))
     ,mpatches.Circle((),color=cmap(0.9))]
legend = axs[plot].legend(c,['Small Blue','Big Red'], handler_map={mpatches.Circle: HandlerEllipse()})
#here's the 'trick', loop through each legend handle and alter their widths.. using the enumerate function to move along sequentially
for i,legend_handle in enumerate(legend.legendHandles):
    legend_handle.width = (10+i*10)

'''

1 个答案:

答案 0 :(得分:1)

您可以从您创建的代理艺术家那里获取尺寸,并将其传递给图例处理程序。

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerPatch
import matplotlib.patches as mpatches

class HandlerEllipse(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
        p = mpatches.Ellipse(xy=center, width=orig_handle.width,
                                        height=orig_handle.height)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]

fig, ax = plt.subplots()
cmap = plt.cm.get_cmap(name='Spectral_r', lut=None)

c = [mpatches.Ellipse((), width=10, height=5, color=cmap(0.1)),
     mpatches.Ellipse((), width=20, height=5, color=cmap(0.9))]
legend = ax.legend(c,['Small Blue','Big Red'], handler_map={mpatches.Ellipse: HandlerEllipse()})

plt.show()

enter image description here