如何在python中为非数字变量制作直方图

问题描述 投票:3回答:3

样本数据

import pandas as pd
import matplotlib.pyplot as plt

dummy = {'id': [1,2,3,4,5], 
        'brand': ['MS', 'Apple', 'MS', 'Google', 'Apple'], 
        'quarter': ['2017Q2', '2017Q2', '2017Q2', '2016Q1', '2015Q1']}

dummyData = pd.DataFrame(dummy, columns = ['id', 'brand', 'quarter'])
dummyData


# id    brand   quarter
# 0 1   MS      2017Q2
# 1 2   Apple   2017Q2
# 2 3   MS      2017Q2
# 3 4   Google  2016Q1
# 4 5   Apple   2015Q1

现在我想使用matplotlib和pandas制作直方图,这里是描述

  • X轴:四分之一
  • Y轴:值的计数
  • 直方图箱:像2017Q2这样的品牌有MS和Apple的两种颜色值
  • 传说:品牌名称

我有一个R背景,它很容易使用ggplot,我想在Python中做同样的事情,但我没有找到任何合适的代码,我得到下面提到的错误

TypeError: Empty 'DataFrame': no numeric data to plot
python pandas dataframe matplotlib histogram
3个回答
3
投票

IIUC,你可以使用groupby + count + unstack + plot -

plt.style.use('ggplot')

dummyData.groupby(['quarter', 'brand'])\
      .brand.count().unstack().plot.bar(legend=True)

plt.show()

enter image description here

作为参考,这是绘制的 -

brand    Apple  Google   MS
quarter                    
2015Q1     1.0     NaN  NaN
2016Q1     NaN     1.0  NaN
2017Q2     1.0     NaN  2.0

2
投票

我相信你需要groupbysize,然后重塑unstackcrosstab

最后的情节由DataFrame.plot.bar

df = dummyData.groupby(['quarter','brand']).size().unstack(fill_value=0)
#alternative solution
#df = pd.crosstab(dummyData['quarter'], dummyData['brand'])
print (df)
brand    Apple  Google  MS
quarter                   
2015Q1       1       0   0
2016Q1       0       1   0
2017Q2       1       0   2

df.plot.bar()

graph


0
投票

Another Alternative

data_frame.attribute_name.value_counts().plot.bar()

Example

iris_data.sample(3)

iris_data.Species.value_counts().plot.bar()

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