How to make a histogram from a list of strings in Python?

前端 未结 8 1248
说谎
说谎 2020-12-03 04:29

I have a list of strings:

a = [\'a\', \'a\', \'a\', \'a\', \'b\', \'b\', \'c\', \'c\', \'c\', \'d\', \'e\', \'e\', \'e\', \'e\', \'e\']

I w

8条回答
  •  天命终不由人
    2020-12-03 05:23

    As @notconfusing pointed above this can be solved with Pandas and Counter. If for any reason you need to not use Pandas you can get by with only matplotlib using the function in the following code:

    from collections import Counter
    import numpy as np
    import matplotlib.pyplot as plt
    
    a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
    letter_counts = Counter(a)
    
    def plot_bar_from_counter(counter, ax=None):
        """"
        This function creates a bar plot from a counter.
    
        :param counter: This is a counter object, a dictionary with the item as the key
         and the frequency as the value
        :param ax: an axis of matplotlib
        :return: the axis wit the object in it
        """
    
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
    
        frequencies = counter.values()
        names = counter.keys()
    
        x_coordinates = np.arange(len(counter))
        ax.bar(x_coordinates, frequencies, align='center')
    
        ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates))
        ax.xaxis.set_major_formatter(plt.FixedFormatter(names))
    
        return ax
    
    plot_bar_from_counter(letter_counts)
    plt.show()
    

    Which will produce

提交回复
热议问题