简体   繁体   English

Plot 条形图来自 Pandas DataFrame

[英]Plot bar graph from Pandas DataFrame

Assuming i have a DataFrame that 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 V1 and V2 by the Hour .我试图创建一个条形 plot 以按Hour比较列V1V2 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)

I get a plot and a legend with all the columns' values and names.我得到一个 plot 和一个包含所有列的值和名称的图例。 How can I modify my code so the plot and legend only displays the columns V1 and V2如何修改我的代码,以便 plot 和图例仅显示列V1V2

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 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 [[]] . 您尝试过的操作是df['V1','V2']这将引发KeyError因为该标签没有正确的列,尽管起初看起来很可笑,您必须考虑传递列表,因此使用双方括号[[]]

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

在此处输入图片说明

A minimal seaborn apporach to plot from pandas dataframe:从 pandas Z6A8064B5DF47945550DZ0553 到 plot 的最小 seaborn 方法

import pandas as pd
import seaborn as sns

random_dict = {
    "classes": ["A", "B", "C"],
    "quantities": [100, 300, 200]
}

df = pd.DataFrame.from_dict(random_dict)
sns.barplot(x="classes", y="quantities", data=df)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM