簡體   English   中英

如何組合兩個直方圖python

[英]How to combine two histograms 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來執行此任務。 我還沒弄明白如何使用Pandas tho繪制兩個直方圖(想看看人們是如何做到的)。

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使用此結構而不是兩個不同長度的pandas數據幀和非數字列。 Pandas的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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM