如何组合两个直方图 python


male[['Gender','Age']].plot(kind='hist', x='Gender', y='Age', bins=50)
female[['Gender','Age']].plot(kind='hist', x='Gender', y='Age', bins=50)

所以基本上,我使用文件中的数据根据性别和年龄创建了两个直方图。从一开始,我就按性别将数据分开,以初步绘制。现在我很难将两个直方图放在一起。

如注释中所述,您可以使用 matplotlib 来完成此任务。我还没有弄清楚如何使用熊猫绘制两个直方图(想看看人们是如何做到这一点的(。

import matplotlib.pyplot as plt
import random
# example data
age = [random.randint(20, 40) for _ in range(100)]
sex = [random.choice(['M', 'F']) for _ in range(100)]
# just give a list of age of male/female and corresponding color here
plt.hist([[a for a, s in zip(age, sex) if s=='M'], 
          [a for a, s in zip(age, sex) if s=='F']], 
         color=['b','r'], alpha=0.5, bins=10)
plt.show()
考虑将数据

帧转换为两列 numpy 矩阵,因为matplotlibhist使用此结构,而不是使用非数字列的两个不同长度的熊猫数据帧。熊猫的join用于绑定两列,MaleAgeFemaleAge

在这里,性别指示器被删除并根据列顺序手动标记。

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
...
# RESET INDEX AND RENAME COLUMN AFTER SUBSETTING
male = df2[df2['Gender'] == "M"].reset_index(drop=True).rename(columns={'Age':'MaleAge'})
female = df2[df2['Gender'] == "F"].reset_index(drop=True).rename(columns={'Age':'FemaleAge'})
# OUTER JOIN TO ACHIEVE SAME LENGTH
gendermat = np.array(male[['MaleAge']].join(female[['FemaleAge']], how='outer'))
plt.hist(gendermat, bins=50, label=['male', 'female'])
plt.legend(loc='upper right')
plt.show()
plt.clf()
plt.close()

最新更新