Single legend item with two lines

后端 未结 2 666
梦如初夏
梦如初夏 2020-12-09 14:30

I\'d like to generate a custom matplotlib legend which, for each entry has two lines for each label as shown in this example:

From some researc

2条回答
  •  北海茫月
    2020-12-09 14:49

    Here is an inadequate solution I have come to after playing around. I post it in case it helps others, but would prefer to do it properly. It uses two columns and the label of the first as a '/' or one could equally use "and".

    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 3)
    fig, axL = plt.subplots()
    axR = axL.twinx()
    
    axL.plot(x, np.sin(x), color='k', label='/')
    axR.plot(x, 100*np.cos(x), color='r', label='label')
    
    axL.set_ylabel('sin(x)', color='k')
    axR.set_ylabel('100 cos(x)', color='r')
    axR.tick_params('y', colors='r')
    
    handlesL, labelsL = axL.get_legend_handles_labels()
    handlesR, labelsR = axR.get_legend_handles_labels()
    handles = handlesL + handlesR
    labels = labelsL + labelsR
    axR.legend(handles, labels, loc='lower center', ncol=2, fontsize=16,
               handletextpad=0.4, columnspacing=0.4)
    

提交回复
热议问题