根据类别绘制两个直方图

时间:2018-10-16 20:57:03

标签: python pandas matplotlib

我试图在同一图上绘制两个直方图,例如here,但基于类别。

我的数据如下:

enter image description here

我想要一个音乐家的直方图​​(编码为“ 1”)和一个非音乐家的直方图​​(0)并在y轴上绘制年龄。

当前代码不起作用(尝试其中的几种解决方案不起作用):

import pandas as pd

import numpy as np

data = pd.read_csv("age-groups.csv", skiprows=[1, 2])

data.columns = ['date', 'age', 'gender', 'musician']

data = data.replace(to_replace="No", value='0')
data = data.replace(to_replace="Yes", value='1')


mornot = np.array(data['musician'])


pd.Categorical(mornot, categories=['nonmusician', 'musician'])

# pd.cut(mornot, 2, labels=["musician", "nonmusician"], retbins=True)


from matplotlib import pyplot

# attempt 1

data.groupby('musician').plot(kind='hist')
pyplot.show()

data['musician'].value_counts().plot(kind='hist')
pyplot.legend(loc='upper right')
pyplot.show()

# attempt 2

pyplot.hist(musician, bins, alpha=0.5, label='musician')
pyplot.hist(nonmusician, bins, alpha=0.5, label='nonmusician')
pyplot.legend(loc='upper right')
pyplot.show()

非常感谢。

0 个答案:

没有答案