Search code examples
matlabdata-visualizationmatlab-figure

How to adjust bar absolute width in MATLAB


I'm confused with the bar with adjustment in MATLAB, for example, when use bar like:

bar(randsample(0:0.0001:1,100),randn(100,1))

I get an image like this: enter image description here

It seems like the bar is too thin to have a good look. After searching for help, I can use the code like:

bar(randsample(0:0.0001:1,100),randn(100,1),50)

and I get this: enter image description here

Seems much better. But if I change the sample number from 100 to 10, the same code won't work.

bar(randsample(0:0.0001:1,10),randn(10,1),50)

enter image description here

I hope I have explained my issue clear. It seems like the third parameter of the bar function is a relative width, which correlates to the input size of the first and second parameter. Can I fix the absolute bar width no matter how many data points input? or there is a better function to draw figures like this? Thanks a lot for any help!


Solution

  • user @am304 is right about the width parameter

    What happened in your code is that you set x values to results from randsample(0:0.0001:1,10)

    If you give your plot a width of 1 it means that 2 bars which are directly next to each other would touch each other with an equally spaced x.

    In your case, you have an irregular x spacing. The width of the bar is determined by the minimum distance between two x values (which you get from randsample()). Sometimes this space - and therefore the width of your bar - is very tiny. Sometimes it is broader.

    Change the with to 1 and make multiple plots. You will notice that two are always touching each other and no one is overlapping and all the others have spaces in between. If you change the width to 50 the plots will somethimes overlap heavily (depending on the randomness from randsample) because your bars are 50 times bigger then the minimum width between two x values.

    In case of your randsample(0:0.0001:1,100) example it is just more likely that two values are close to each other, therefore increasing the width helps you see something (because the bars overlap).