【问题标题】:Plot a histogram with the x axis values based on the height of the column根据列的高度绘制带有 x 轴值的直方图
【发布时间】:2013-03-28 00:32:18
【问题描述】:

假设我有以下内容:

[1,5,1,1,6,3,3,4,5,5,5,2,5]

Counts: {1:3, 2:1, 3:2, 4:1, 5:5, 6:1}

现在,我想打印一个在 x 轴上排序的直方图,如下所示:

传统的直方图是:

        X  
        X
X       X  
X   X   X
X X X X X X
1 2 3 4 5 6

我想要的是:

        X  
        X
      X X  
    X X X
X X X X X 
2 4 3 1 5 

我当前的绘图代码是:

plt.clf()
plt.cla()
plt.xlim(0,1)
plt.axvline(x=.85, color='r',linewidth=0.1)
plt.hist(correlation,2000,(0.0,1.0))
plt.xlabel(index[thecolumn]+' histogram')
plt.ylabel('X Data')

savefig(histogramsave,format='pdf')

请帮助我了解如何做到这一点...我知道我之前发布过类似的问题,但我相信我不清楚...

【问题讨论】:

    标签: python matplotlib plot histogram


    【解决方案1】:

    直方图不是您要查找的图表。使用条形图。

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = [1, 5, 1, 1, 6, 3, 3, 4, 5, 5, 5, 2, 5]
    correlation = [(i, data.count(i)) for i in set(data)]
    correlation.sort(key=lambda x: x[1])
    
    labels, values = zip(*correlation)
    
    indexes = np.arange(len(correlation))
    width = 1
    
    plt.bar(indexes, values, width)
    plt.xticks(indexes + width * 0.5, labels)
    plt.show()
    

    编辑:对于大量数据,最好使用collections.Counter 而不是count 的列表理解。


    这是更快地归档相同结果的方法(既没有条形图也没有历史记录):

    from collections import Counter
    import numpy as np
    import matplotlib.pyplot as plt
    data = np.random.random_integers(0, 10**4, 10**5)
    correlation = Counter(data).items()
    correlation.sort(key=lambda x: x[1])
    labels, values = zip(*correlation)
    indexes = np.arange(len(correlation))
    
    plt.plot(indexes, values)
    plt.fill_between(indexes, values, 0)
    plt.show()
    

    【讨论】:

    • 在这里使用count 来处理大列表效率低下,因为它会为每个唯一元素遍历列表。
    • @Jared 同意了。编辑了答案。感谢您指出这一点。
    • 事情是...我有一个包含大约 9000 个相关值的大列表,因此 0
    • 如题,对于如此庞大的数据集,您将如何扩展它?
    • 我现在不明白这个问题。您是否需要每个栏下的标签(如您的示例中)?如果是这样,您想如何用 9000 个值显示它?没有它们,你所需要的只是对你的相关性进行排序。这是expansion 用于大型(10^4)数据集(我删除了宽度和标签)
    猜你喜欢
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    相关资源
    最近更新 更多