从Pandas DataFrame绘制条形图

问题描述 投票:30回答:1

假设我有一个看起来像这样的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

我试图创建一个条形图来比较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)

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

python pandas plot
1个回答
54
投票

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

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

你尝试的是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()

© www.soinside.com 2019 - 2024. All rights reserved.