Subheadings for categories within matplotlib custom legend

折月煮酒 提交于 2019-11-26 11:27:03

问题


I have a a figure that looks like this:

\"enter

I\'d like to make a legend that looks like this:

\"enter

How can I do that?


UPDATE:

Note that this legend has a frame with an edgecolor: a valid answer will include this. The legend should also be embedded in the axes.

The legend I want might not be achievable using ax.legend(). A great answer would be one which shows how to build my desired legend (exactly as shown) manually with patches and texts, or whatever matplotlib methods that make sense.


回答1:


Separate headings for D and A lines:

from matplotlib.pyplot import *
ds = [1,2,3]
dc = [1.1, 1.9, 3.2]
asim = [1.5, 2.2, 3.1]
ac = [1.6, 2.15, 3.1]

categories = ['simulated', 'calculated']

p1, = plot(ds, 'ko', label='D simulated')
p2, = plot(dc, 'k:', label='D calculated')
p3, = plot(asim, 'b+', label='A simulated')
p4, = plot(ac, 'b-', label='A calculated')
p5, = plot([0], marker='None',
           linestyle='None', label='dummy-tophead')
p7, = plot([0],  marker='None',
           linestyle='None', label='dummy-empty')

leg3 = legend([p5, p1, p2, p5, p3, p4],
              [r'$D_{etc}$'] + categories + [r'$A_{etc}$'] + categories,
              loc=2, ncol=2) # Two columns, vertical group labels

leg4 = legend([p5, p7, p5, p7, p1, p2, p3, p4],
              [r'$D_{etc}$', '', r'$A_{etc}$', ''] + categories + categories,
              loc=4, ncol=2) # Two columns, horizontal group labels

gca().add_artist(leg3)

#If there isn't a big empty spot on the plot, two legends:
#leg1 = legend([p1, p2], categories, title='D_etc', loc=0)
#leg2 = legend([p3, p4], categories, title='A_etc', loc=4)
#gca().add_artist(leg2) 

show()



来源:https://stackoverflow.com/questions/21570007/subheadings-for-categories-within-matplotlib-custom-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!