【问题标题】:Best way to plot categorical data [closed]绘制分类数据的最佳方法[关闭]
【发布时间】:2015-04-08 07:13:00
【问题描述】:

我有一个这样的列表:

 gender = ['male','female','male','female']

使用 matplotlib 将此列表的计数绘制为条形图的最简单方法是什么?

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    使用collections.Counter(),您可以轻松计算列表中元素的频率。

    然后您可以使用以下代码创建bar plot

    gender = ['male','male','female','male','female']
    
    import matplotlib.pyplot as plt
    from collections import Counter
    
    c = Counter(gender)
    
    men = c['male']
    women = c['female']
    
    bar_heights = (men, women)
    x = (1, 2)
    
    fig, ax = plt.subplots()
    width = 0.4
    
    ax.bar(x, bar_heights, width)
    
    ax.set_xlim((0, 3))
    ax.set_ylim((0, max(men, women)*1.1))
    
    ax.set_xticks([i+width/2 for i in x])
    ax.set_xticklabels(['male', 'female'])
    
    plt.show()
    

    结果图表:

    【讨论】:

    • 如果您希望类别出现在 y 轴上怎么办?
    • @FC84 对于水平条形图,check this
    • @FC84 还要检查orientation='horizontal' here
    【解决方案2】:
    uValues = list( set( gender))
    xVals = range( 0, len( uValues))
    yVals = map( lambda x: gender.count( uValues[x]), xVals)
    
    import pylab
    pylab.bar( xVals, yVals)
    

    当然你不会在 x-ticks 上有文字,但情节是正确的

    【讨论】:

      猜你喜欢
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 2020-04-17
      • 2016-08-25
      • 2012-01-01
      相关资源
      最近更新 更多