Plotting histogram of list of tuplets matplotlib

后端 未结 1 1068
挽巷
挽巷 2021-01-23 03:46

I have a list of tuplets as so

k = [(8, 8),(10, 10),(8, 8),
 (8, 8),(12, 12),(7, 7),(8, 8),
 (9, 9),(10, 10),(10, 10),(8, 8),(9, 9),(13, 13),
 (10, 10),(8, 8),(         


        
相关标签:
1条回答
  • 2021-01-23 03:55

    A histogram (numpy.hist, plt.hist) is usually on continuous data, that you can easily separate in bins.

    Here you want to count the identical tuples: you can use collection.Counter

    from collections import Counter
    k = [(8, 8),(10, 10),(8, 8),
     (8, 8),(12, 12),(7, 7),(8, 8),
     (9, 9),(10, 10),(10, 10),(8, 8),(9, 9),(13, 13),
     (10, 10),(8, 8),(8, 8),(7, 7)]
    
    c=Counter(k)
    >>> Counter({(8, 8): 7, (10, 10): 4, (9, 9): 2, (7, 7): 2, (13, 13): 1, (12, 12): 1})
    

    After some formatting, you can use plt.bar to plot the count of each tuple, in a histogram fashion.

    # x axis: one point per key in the Counter (=unique tuple)
    x=range(len(c))
    # y axis: count for each tuple, sorted by tuple value
    y=[c[key] for key in sorted(c)]
    # labels for x axis: tuple as strings
    xlabels=[str(t) for t in sorted(c)]
    
    # plot
    plt.bar(x,y,width=1)
    # set the labels at the middle of the bars
    plt.xticks([x+0.5 for x in x],xlabels)
    

    0 讨论(0)
提交回复
热议问题