Search code examples
pythonpandasmatplotlibstatisticshistogram

How can I plot Histogram for discrete data using python matplotlib?


Here is the data, How can I plot a histogram using matplotlib on this Discrete data.

X   F
3   3
4   3
5   5
6   3
7   4
8   4
9   3
10  4
11  2
12  2
13  3
14  1
15  2
16  5
17  2
18  1
19  2
20  1

Solution

  • Your data is already a histogram (don't need to bin any observations here, is that right?), so I suppose you just need to plot it.

    # First read in the data into a dataframe in this case.
    data = """
    3   3
    4   3
    5   5
    6   3
    7   4
    8   4
    9   3
    10  4
    11  2
    12  2
    13  3
    14  1
    15  2
    16  5
    17  2
    18  1
    19  2
    20  1""".split();
    data = list(map(int, data))
    data = pd.DataFrame({'X': data[::2], 'F': data[1::2]})
    
    # Use matplotlib to draw a bar chart. Draw it with histogram style.
    plt.bar(data.X, data.F, align='edge', width=1, edgecolor='k');
    

    histogram example