Disappointed by the lack of control in Matlab’s bar function and wanting to create visually-pleasing bar charts, I’ve created the barmod function. This function gives you control over; the pixel height of the plot, the aspect ratio, bar offset (spacing between individual bars in groups), bar group offset (spacing between groups of bars), x-limit offset (space between data and plot extents on either side of plot), y-limit offset (space between data and plot extents on top and bottom of plot), and the labels of the categories of your bar chart. This function is a modification of Cris Luengo’s solution to controlling the space between bar groups (https://stackoverflow.com/a/50432076).
In greater detail, the barmod function’s eight inputs in order are:
x – your bar chart data (size NBG x n, where “NBG” is the number of bar groups and “n” is the number of bars/group)
yhp – plot height in pixels
ar – aspect ratio (width/height)
bo – bar offset (spacing between individual bars within groups—input as ratio to individual bar width)
bgo – bar group offset (spacing between groups of bars—input as ratio to *total bar group width)
xlimo – x-limit offset (space between left/right extents of bar chart data and left/right extents of plot, respectively—input as ratio to total bar group width)
ylimo – y-limit offset (space between top/bottom extents of bar chart data and top/bottom extents of plot, respectively—input as ratio to total bar group width)
labels – labels corresponding to bar groups.
*total bar group width is the sum of the widths of each bar and the widths of each bar offset in a group
The default for each input is:
x: random 1-to-5 x 1-to-5 barchart†
yhp: 500 (pixels)
bo: 0 (no gap between bars within a group)
labels: strcat(‘title’,num2str(i)), where i is the bar group index
†With style ‘hist’, the bar function in matlab does not display data inputs of a single datum, and therefore neither does this function.
As far as plot styling and color (including a y = 0 baseline), I leave that to the user (the default color map is parula).
Check out barmod_demo for examples, limits of functionality, workarounds, and more!
Hunter Pruett (2021). barmod (https://github.com/hunterpruett/barmod/releases/tag/v1.0), GitHub. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Inspired by: superbar
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!