【问题标题】:How to display different values of the same column in plot graph/chart如何在绘图/图表中显示同一列的不同值
【发布时间】:2022-01-07 12:31:33
【问题描述】:

列类有 2 个值选项,“b”或“s”。我正在尝试显示一个图形/图表,显示有多少是“b”,有多少是“s”。当它们都在同一列时,我不知道该怎么做。

当前代码显示的是散点图,但我想使用“类”列中的数据。

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

#df = df.groupby('class')['class'].count()
#print(df)

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['class'] = ['Benign','Malware','Benign','Malware','Malware']

# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))

for n, grp in df.groupby('class'):
    ax.scatter(x = "x", y = "y", data=grp, label=n)
ax.legend(title="Label")

plt.show()

【问题讨论】:

  • “b”有多少,“s”有多少是什么意思?
  • 数据有一个名为“class”的列,该列中的值为“b”或“s”。我试图仅从该列显示有多少条目是“b”以及有多少是“s”

标签: python matplotlib jupyter-notebook


【解决方案1】:

不要按类和循环分组,而是聚合(使用value_counts)然后绘制:

df['class'].value_counts().plot.bar()

或者使用 matplotlib 的函数:

s = df['class'].value_counts()
ax.bar(s.index, s)

输出:

【讨论】:

  • 这正是我想要做的!谢谢
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2022-07-22
  • 1970-01-01
  • 2021-11-26
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多