Building a legend with the correct python labels

I have a data frame and I want to build a legend with 'A', 'B' and 'C', however, that I only created a legend labeled 'A':

data = {'A1_mean': [0.457, 1],
         'A2_median': [0.391,1],
         'A3_range': [0.645,1],
         'A4_std': [0.111,1],
         'B1_mean': [0.132,3],
         'B2_median': [0.10,3],
         'B3_range': [0.244,3],
         'B4_std': [0.297,3],
         'C1_mean': [0.286,2],
         'C2_median': [0.231,2],
         'C3_range': [0.554,2],
         'C4_std': [0.147,2]}
df = pd.DataFrame(data).T
color = {1:'red',2:'green',3:'blue'}
ax=df[0].plot(kind='bar',color=df[1].map(color).tolist())
ax.legend(['A','B','C'])

gives:

enter image description here

How can I change this so that I have a legend with AB and C with the corresponding color (A: red, B: blue, C: green)?

+4
source share
1 answer

In the Legend Guide, you can put Proxy Artists in the legend:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

data = {'A1_mean': [0.457, 1],
         'A2_median': [0.391,1],
         'A3_range': [0.645,1],
         'A4_std': [0.111,1],
         'B1_mean': [0.132,3],
         'B2_median': [0.10,3],
         'B3_range': [0.244,3],
         'B4_std': [0.297,3],
         'C1_mean': [0.286,2],
         'C2_median': [0.231,2],
         'C3_range': [0.554,2],
         'C4_std': [0.147,2]}
df = pd.DataFrame(data).T
color = {1:'red',2:'green',3:'blue'}
labels = ['A','C','B']
fig, ax = plt.subplots()
df[0].plot(ax=ax, kind='bar', color=df[1].map(color))

handles = []
for i, c in color.items():
    handles.append(mpatches.Patch(color=c, label=labels[i-1]))
plt.legend(handles=handles, loc='best')
# auto-rotate xtick labels
fig.autofmt_xdate()
plt.show()

enter image description here

+1
source

Source: https://habr.com/ru/post/1628863/


All Articles