我有一个数据框,我想绘制一个带有’A’,’B’和’C’的图例但是,我只创建了带有’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'])
得到:
如何改变这一点,以便我有一个A B和C的传奇,具有适当的颜色(A:红色,B:蓝色,C:绿色)?
最佳答案 根据
Legend guide,您可以将代理艺术家放置在图例中:
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()