从 Pandas DataFrame 绘制条形图 [英] Plot bar graph from Pandas DataFrame

查看:94
本文介绍了从 Pandas DataFrame 绘制条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个看起来像这样的 DataFrame:

Assuming i have a DataFrame that looks like this:

Hour | V1 | V2 | A1 | A2
 0   | 15 | 13 | 25 | 37  
 1   | 26 | 52 | 21 | 45 
 2   | 18 | 45 | 45 | 25 
 3   | 65 | 38 | 98 | 14

我正在尝试创建一个条形图来按 Hour 比较 V1V2 列.当我这样做时:

Im trying to create a bar plot to compare columns V1 and V2 by the Hour. When I do:

import matplotlib.pyplot as plt
ax = df.plot(kind='bar', title ="V comp",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Hour",fontsize=12)
ax.set_ylabel("V",fontsize=12)

我得到了一个包含所有列的值和名称的图和一个图例.如何修改我的代码,以便绘图和图例仅显示列 V1V2

I get a plot and a legend with all the columns' values and names. How can I modify my code so the plot and legend only displays the columns V1 and V2

推荐答案

要仅绘制选定的列,您可以通过将列表传递给下标运算符来选择感兴趣的列:

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

您尝试的是 df['V1','V2'] 这将引发 KeyError 正确地不存在带有该标签的列,尽管它看起来很有趣首先,您必须考虑您正在传递一个列表,因此需要使用双方括号 [[]].

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

这篇关于从 Pandas DataFrame 绘制条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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