如何获取matplotlib条形图以匹配python终端中的数字计数

时间:2017-07-04 19:44:45

标签: python pandas matplotlib bar-chart

我的主要目标是与我的数字输出和视觉输出保持一致。但是,我似乎无法与他们匹敌。

这是我使用python 3.x的设置:

df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])

接下来我在matplotlib中设置了条形图:

x = df['Expo']
N = len(x)
y = range(N)
width = 0.125
plt.bar(x, y, width, color="blue")
fig = plt.gcf();

制作了漂亮漂亮的图表:enter image description here

但是,使用此代码段来检查并查看两个类的实际数字计数是什么......

print("Class 1: "+str(df['Expo'].value_counts()[1]),"Class 2: "+str(df['Expo'].value_counts()[2])) 

我得到以下内容:

  

Class 1:85 Class 2:70

由于我在数据框中有155条记录,因此在数字上这是有道理的。条形图中的单个条形在155处不会。

我提前感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我想这就是你所追求的:

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


df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])

# Count number of '1' and '2' elements in df
N1, N2 = len(df[df['Expo'] == 1]), len(df[df['Expo'] == 2])
width = 0.125
# Plot the lengths in x positions [1, 2]
plt.bar([1, 2], [N1, N2], width, color="blue")
fig = plt.gcf()
plt.show()

哪个产生

enter image description here

答案 1 :(得分:1)

您可以使用直方图

plt.hist(df["Expo"])

enter image description here

或指定垃圾箱

plt.hist(df["Expo"], bins=[0.5,1.5,2.5], ec="k")
plt.xticks([1,2])

enter image description here