matplotlib条形图从类别数据框列添加图例 [英] matplotlib bar plot add legend from categories dataframe column

查看:68
本文介绍了matplotlib条形图从类别数据框列添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试添加图例,根据我的示例,该图例应输出:

  1. 带有水果一词和
  2. 的红色正方形
  3. 带有单词的绿色方块素食.

我尝试了几种方法(下面的示例只是许多试验中的一种),但是我无法使其正常工作.

有人可以告诉我如何解决这个问题吗?

 将pandas导入为pd从matplotlib导入pyplot作为plt数据= [['apple','fruit',10],['nanaba','fruit',15],['salat','veggie',144]]数据= pd.DataFrame(数据,列= ['对象','类型','值'])颜色= {'水果':'红色','蔬菜':'绿色'}c = data ['Type'].apply(lambda x:colors [x])条= plt.bar(数据['对象'],数据['值'],颜色= c,标签=颜色)plt.legend() 

解决方案

为不在轴上的对象创建图例的通常方法是创建代理艺术家,如

I try to add the legend which should, according to my example, output:

  1. a red square with the word fruit and
  2. a green square with the word veggie.

I tried several things (the example below is just 1 of the many trials), but I can't get it work.

Can someone tell me how to solve this problem?

import pandas as pd
from matplotlib import pyplot as plt
data = [['apple', 'fruit', 10], ['nanaba', 'fruit', 15], ['salat','veggie', 144]] 
data = pd.DataFrame(data, columns = ['Object', 'Type', 'Value']) 

colors = {'fruit':'red', 'veggie':'green'}           
c = data['Type'].apply(lambda x: colors[x])

bars = plt.bar(data['Object'], data['Value'], color=c, label=colors)
plt.legend()

解决方案

The usual way to create a legend for objects which are not in the axes would be to create proxy artists as shown in the legend guide

Here,

colors = {'fruit':'red', 'veggie':'green'}         
labels = list(colors.keys())
handles = [plt.Rectangle((0,0),1,1, color=colors[label]) for label in labels]
plt.legend(handles, labels)

这篇关于matplotlib条形图从类别数据框列添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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