在matplotlib中手动创建图例

时间:2018-06-13 06:46:22

标签: python matplotlib legend

我有以下代码来绘制条形图 - 有6种但是代码将它们分成三个颜色分组。

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

enter image description here

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

任何帮助非常感谢

4 个答案:

答案 0 :(得分:1)

您可以尝试这种方式:

for _ in dat['sp']: #looping here keeps the order
if _ not in grps:
    grps.append(_)

i=0
for grp in grps:
    dat.loc[dat['sp']==grp,'meanGrs']= dat.loc[dat['sp']==grp,'growth'].mean()
    dat.loc[dat['sp']==grp,'sems']= dat.loc[dat['sp']==grp,'growth'].sem()
    plt.bar(i, dat.loc[dat['sp']==grp,'meanGrs'], 
              yerr=dat.loc[dat['sp']==grp,'sems'], align = 'center', 
              alpha = 0.5, color = dat.loc[dat['sp']==grp,'cols'])
    i=i+1
    plt.legend(('group 1', 'group 2', 'group 3', 'group 4'))
    plt.show()

答案 1 :(得分:0)

把参数"标签"在plt.bar中:

plt.bar(y_pos, meanGrs, yerr=sems, align = 'center', alpha = 0.5, color = cols, label=cols)

答案 2 :(得分:0)

这就是工作:

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)

答案 3 :(得分:0)

我不太确定在这种情况下决定哪个组是什么。但如果这是任意的,你可以动态创建组。

legenditems = [(plt.Rectangle((0,0),1,1, color=c, alpha=0.5), "group "+str(i+1))
                 for i,c in enumerate(np.unique(cols))]
plt.legend(*zip(*legenditems))

enter image description here