matplotlib - Legend in separate subplot

后端 未结 1 931
执念已碎
执念已碎 2020-12-31 11:56

I am plotting an array of pie charts, each using the same two colors for the same two types of data.

plt.figure(num=None, figsize=(6, 8))
for i in range(len         


        
1条回答
  •  春和景丽
    2020-12-31 12:49

    You can call legend() only once:

    import numpy as np
    import pylab as pl
    
    for i in xrange(1, 5):
        pl.subplot(220+i)
        pl.pie([i,2], labels=["a","b"], autopct='%1.1f%%')
    
    l = pl.legend(title="sample")
    pl.show()
    

    enter image description here

    or if you want the legend in a new axes, just create a dummy pie, and create legend for it, and then hide the dummy pie:

    import numpy as np
    import pylab as pl
    
    for i in xrange(1, 5):
        pl.subplot(220+i)
        pl.pie([i,2], labels=["a","b"], autopct='%1.1f%%')
    
    fig = pl.gcf()
    axe = fig.add_axes([0.4,0.4,0.2,0.2])
    
    pie = pl.pie([1,1], labels=["a","b"])
    l = pl.legend(title="sample", loc="center")
    for group in pie:
        for x in group:
            x.set_visible(False)
    
    pl.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题