【问题标题】:How to combine two histograms python如何组合两个直方图python
【发布时间】:2017-09-12 09:53:14
【问题描述】:
male[['Gender','Age']].plot(kind='hist', x='Gender', y='Age', bins=50)
female[['Gender','Age']].plot(kind='hist', x='Gender', y='Age', bins=50)

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

【问题讨论】:

  • 你的意思是在同一张图中?
  • 是的,我需要两个直方图都在同一个图表上。
  • 我以前看过这个,但是当我做类似于 plt.hist(male, label='x') plt.hist(female, label='y') 的事情时,它给了我 TypeError:未大小对象的 len()
  • 然后显示产生这个错误的代码并询问这个错误..

标签: python pandas histogram


【解决方案1】:

正如评论中提到的,您可以使用 matplotlib 来完成此任务。我还没有弄清楚如何使用 Pandas 绘制两个直方图(想看看人们是如何做到的)。

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()

【讨论】:

    【解决方案2】:

    考虑将数据帧转换为两列 numpy 矩阵,因为 matplotlibhist 使用这种结构,而不是两个不同长度的非数字列的 pandas 数据帧。 Pandas 的join 用于绑定MaleAgeFemaleAge这两列。

    这里,Gender 指示符被移除并根据列顺序手动标记。

    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()
    

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2020-10-24
      • 2021-09-05
      • 1970-01-01
      • 2017-06-07
      • 2014-07-18
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多