matplotlib-图例在单独的子图中 [英] matplotlib - Legend in separate subplot

查看:86
本文介绍了matplotlib-图例在单独的子图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制一个饼图数组,每个饼图对于相同的两种类型的数据都使用相同的两种颜色.

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?

推荐答案

您只能调用legend()一次:

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()

或者如果要在新轴上使用图例,只需创建一个虚拟饼图,并为其创建图例,然后隐藏该虚拟饼图:

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()

这篇关于matplotlib-图例在单独的子图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆