在matplotlib中手动创建图例 [英] create legend manually in matplotlib

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

问题描述

我有以下代码来绘制条形图-有6种,但是代码将它们分为三个彩色组.

I have the following code to plot a bar graph - there are 6 species but the code groups them into three coloured groupings.

然后我想用三种颜色制作三组的传奇.但是,图例仅包含第一个分组(颜色正确!),然后忽略其他分组(见图)

I then want to make a legend of the three groups with three colours. However, the legend only features the first grouping (which is colored correctly!) and then ignores the other groupings (see image)

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#create data frame
G = pd.DataFrame(np.random.normal(100,20,size=(30, 1)), columns=list('G'))
T = []
for i in range(1,7):
    for j in range(5):
        T.append('Species'+repr(i))
T = pd.DataFrame(np.array(T).reshape(30,1), columns = list("T"))
cols = ['g','b','k']
C=[]
for i in range(3):
    for j in range(10):
        C.append(cols[i])
C = pd.DataFrame(np.array(C).reshape(30,1), columns = list("C"))
dat = pd.concat([G, C, T], axis = 1)
dat.columns = ['growth', 'cols', 'sp']

#begin code to make plot
grps = sorted(list(set(list(dat['sp']))))
meanGrs=[]
sems=[]
cols=[]
y_pos = np.arange(len(grps))
for grp in grps:
    qw = 'sp == "' + grp + '"'
    meanGrs.append(dat.query(qw)['growth'].mean())
    sems.append(dat.query(qw)['growth'].sem())
    cols.append(str(dat.query(qw)['cols'].max()))

plt.bar(y_pos, meanGrs, yerr=sems, align = 'center', alpha = 0.5, color = cols, label = cols)
plt.legend(('group 1', 'group 2', 'group 3'))
plt.xticks(y_pos, grps, ha = 'right', rotation = 45)
plt.show()

非常感谢任何帮助

推荐答案

这可以完成工作:

import matplotlib.patches as mpatches

l1 = mpatches.Patch(color='k', label='group 1')
l2 = mpatches.Patch(color='b', label='group 2')
l3 = mpatches.Patch(color='g', label='group 3')
plt.legend(handles=[l1, l2, l3)

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

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