matplotlib: 2 different legends on same graph

前端 未结 4 2039
清歌不尽
清歌不尽 2020-12-02 11:08

I have a plot where different colors are used for different parameters, and where different line styles are used for different algorithms. The goal is to compare the results

4条回答
  •  旧巷少年郎
    2020-12-02 11:30

    What about using a twin ghost axis?

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    
    colors = ['b', 'r', 'g', ]
    styles = ['-', '--', '-.']
    
    for cc, col in enumerate(colors):
        for ss, sty in enumerate(styles):
            print(cc, ss)
            ax.plot([0, 1], [cc, ss], c=colors[cc], ls=styles[ss])
    
    for cc, col in enumerate(colors):
        ax.plot(np.NaN, np.NaN, c=colors[cc], label=col)
    
    ax2 = ax.twinx()
    for ss, sty in enumerate(styles):
        ax2.plot(np.NaN, np.NaN, ls=styles[ss],
                 label='style ' + str(ss), c='black')
    ax2.get_yaxis().set_visible(False)
    
    ax.legend(loc=1)
    ax2.legend(loc=3)
    
    plt.show()
    

提交回复
热议问题