Python 从 Pandas DataFrame 绘制条形图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29498652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:39:50  来源:igfitidea点击:

Plot bar graph from Pandas DataFrame

pythonpandasplot

提问by Alfonso

Assuming i have a DataFramethat looks like this:

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

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

Im trying to create a bar plot to compare columns V1and V2by the Hour. When I do:

我试着去创建一个柱状图来比较列V1V2Hour。当我做:

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)

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 V1and V2

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

采纳答案by EdChum

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)

What you tried was df['V1','V2']this will raise a KeyErroras 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 [[]].

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

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

enter image description here

在此处输入图片说明