【问题标题】:Trouble graphing two series' on python histogram在 python 直方图上绘制两个系列的问题
【发布时间】:2020-04-22 12:14:49
【问题描述】:

我正在尝试从导入的 CSV 文件 (data_dict) 的不同列中绘制直方图。我正在尝试解决下面的问题 - 当我输入以下代码时会出现轴,但是,绘图不会。我将如何绘制这些?非常感谢。

问题

编写代码,按年龄分别绘制女性和男性事故数量的直方图。使用 10 年的垃圾箱。在同一个图上绘制两个分布。

gender1 = np.array(data_dict['Gender'])
age1 = np.array(data_dict['Age'])

age_females = age1[np.where(gender1 == 'Female')]
age_males = age1[np.where(gender1 == 'Male')]


plt.hist(age_males,label='Males',alpha=0.5)
plt.hist(age_females,label='Females',alpha=0.5)
plt.legend()
plt.title('Histogram of Accidents by Age and Genders')
plt.xlabel('Age')
plt.ylabel('Accidents')
plt.xticks(ticks=np.arange(10,110,step=10),labels=(10,20,30,40,50,60,70,80,90,100))
print 

【问题讨论】:

    标签: python csv matplotlib


    【解决方案1】:

    对我来说,代码看起来没问题。我运行了以下内容:

    import numpy as np
    import matplotlib.pyplot as plt
    
    a = np.array([i for i in range(50)])
    b = np.array([i for i in range(50,100)])
    plt.hist(a,label='Males',alpha=0.5)
    plt.hist(b,label='Females',alpha=0.5)
    plt.legend()
    plt.title('Histogram of Accidents by Age and Genders')
    plt.xlabel('Age')
    plt.ylabel('Accidents')
    plt.xticks(ticks=np.arange(10,110,step=10),labels=(10,20,30,40,50,60,70,80,90,100))
    plt.show()
    

    得到了这个情节:

    你能否重现这张图片,如果可以,你确定你的 age_-arrays 包含所需的数据吗?

    根据评论编辑: 好吧,这取决于您的字典实际包含的格式。尝试让你的数组变成这种格式:

    gender1 = np.array(['male', 'male', 'male', 'female', 'female']) 
    age1 = np.array([22,25,23,40,60]) 
    
    age_females = age1[np.where(gender1=='female')] 
    age_males = age1[np.where(gender1=='male')] 
    

    虽然有更优雅的方法来进行索引,但如果你从字典中得到任何内容到这个数组形式,这应该可以工作。

    【讨论】:

    • 我需要找到男性和女性的年龄 - 即来自 (data_dict['Age']) 的年龄,其中来自 (data_dict['Gender']) 的性别是男性,然后还有性别来自 (data_dict['Gender']) 是女性。目前,我无法获得男性和女性的单独年龄值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2019-06-01
    • 2021-09-03
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多