matplotlib 从Pandas DataFrame绘制条形图

k4ymrczo  于 2023-03-19  发布在  其他
关注(0)|答案(3)|浏览(191)

假设我有一个如下所示的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

我试图创建一个条形图来比较V1V2列与Hour列。

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列?

6tr1vspr

6tr1vspr1#

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

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

wz1wpwve

wz1wpwve2#

从Pandas Dataframe 绘制的最小海上方法:

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)

8yparm6h

8yparm6h3#

列标签可以作为轴标签传递(y轴允许多个列标签),而且从panda 1.1开始,轴标签也可以传递到plot()调用中。

df.plot(x='Hour', y=['V1', 'V2'], kind='bar', title="V comp", figsize=(12,6), ylabel='V', rot=0);

相关问题