Search code examples
matlabhistogrambar-chartmatlab-figurefrequency

How to create a frequency histogram in MATLAB?


I'm trying to plot my data in a histogram. I have 8 ranges, with frequencies of 6, 12, 17, 21, 28, 25, 19, and 15 respectively. However, if I plug these values into an array and run the histogram command, I get an image with vertical bars running straight through the top and tons of white space in between.

v = [6 12 17 21 28 25 19 15]
histogram(v)

If I create a bar graph, it works fine but I can't find a way to remove the whitespace between bars. How can I create a histogram with the frequency being the y-axis and each range be labeled on the x-axis?


Solution

  • Use the BarWidth property of bar to change the separation. Setting to 1 means no separation.

    bar(v,'BarWidth',1);
    

    Alternatively, you can use the Style argument to change the style from grouped to histogram format using hist. i.e.

    bar(v,'hist');
    

    For the given data, both of the above approaches give:

    output