MATLAB: Creating a barplot with assigned bar width and color using a ‘categorical mask’

bar widthbarplot

I have three arrays:
x contains the width of each single bar, cumulative value of this array gives the maximum value on x axis eg: [1, 1.5, 0.7, 2,0.2] so maximum x value is 5.2
y contains the height of each bar eg: [-2, 3, 7, 10]
c type of bar eg: [apple, orange, plum, strawberry,apple]
I'd like to plot a barplot in which each bar has an assigned color related to its type, and an assigned width.
Cannot find a way to set these two caracteristic of the bars.

Best Answer

Try this
x = [1, 1.5, 0.7, 2,0.2];
y = [-2, 3, 7, 10, 4]; % <<==== 5th element is added to y to make it of same length as x
labels = {'apple', 'orange', 'plum', 'strawberry', 'apple'};
x_points = movmean(cumsum([0 x]), 2, 'Endpoints', 'discard');
b = gobjects(1, numel(x_points));
ax = axes();
hold(ax);
for i=1:numel(x_points)
b(i) = bar(x_points(i), y(i), 'BarWidth', x(i));
end
legend(labels, 'Location', 'northwest');