MATLAB: Fixing the absolute bar width on ‘bar’ plot

barMATLABwidth

When using the 'bar' function, is it somehow possible to fix the absolute bar width? I have multiple bar figures that at the moment have different bar widths (even with the same x-axis), but I would like to have the bars look the same.
(Matlab R2015b)

Best Answer

Well, that's bizarre-looking on the surface will grant...I'm not sure how to fix up the bar widths directly but I can give you a workaround kludge that will cause the bars to look like they do for the second.
Using
bar([x1 x1(end)+0.01],[y1 nan]
will cause the narrow bars which is owing to the difference in minimum spacing between the two x vectors by some internal logic. In the first case min(diff(x1)) --> 1 where as with x2 the minimum bar separation is 0.027 with the particular set of rn's; that will, obviously be different from run to run but is bound to be <<1 for this many values.
Augmenting the integer-valued vector with a value that is only a short dx from an existing value (I just chose last for convenience in placement in the [] expression) causes the need to have closely-spaced bars as does the given x2; using a NaN for the corresponding y2 makes for the required matching vector lengths but is silently ignored so doesn't affect the displayed plot.
If get a chance, you might check if your release still has bar as an m-file and see if could find the subject logic that defines that subsequent width for the objects; again I've got other commitments so can't do that level of snooping at the moment.(*)
Hopefully that will give you a workaround that can live with...if it's the other way you want the data to look, that can't be as then the bars are wider than the x-spacing; you'd have to group via hist. Hence, I presume you'd prefer the first of your original figures to look like the second that is the goal.
(*) I did open the file; I'd forgotten the guts are in some helper functions makebars is the main one. I see that inside it if the x-spacing is unequal that it then sets the width based on the minimum spacing between points so, in fact, it does basically what I thought from the above; your two cases both are unequally-spaced, but the magnitude difference in the minimum difference causes enough difference in the computed width internally to be very noticeable--making the first roughly the same magnitude creates similar-looking result.
Related Question