Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

python - matplotlib - Legend in separate subplot

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(data_1)):
    plt.subplot(sp_rows, sp_cols, i+1)
    fracs = [data_1[i], data_2[i]]
    plt.pie(fracs, autopct='%1.1f%%')

pp.savefig()

Obviously it doesn't make sense to plot a legend for every one of these charts, since they are all the same. So is there any way I can plot a single legend into a separate subfigure at the end?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...