Lee Sande
Lee Sande

Reputation: 467

matlab bar groups centered at specified location on the x-axis

Suppose one would like to plot 2 sets of data with unequal number of elements

X=[1.1 1.4 1.2 1.1];
Y=[1.4 1.4 1.1]; 

I can use boxplot

boxplot([X Y],[1 1 1 1 2 2 2]) 

to plot these, however there is no function like this for bar. i.e. I would like to plot the bars for each value of X and each value of Y but the values in X should cluster together and should be away from the bars in Y. Ideally In addition to the group, one would also like to specify a third parameter which would specify where on the x-axis should the bars be centred (say in my case [2 11]-- one value for each group).

Does anyone have such a function? I've checked matlabcentral and haven't found what I'm looking for. thanks L

Upvotes: 0

Views: 3498

Answers (2)

alexplanation
alexplanation

Reputation: 1498

This is just a hack, but it may be good enough for starters:

X = [1.1 1.4 1.2 1.1]
Y = [1.4 1.4 1]
Y(end+1) = NaN
bar([X; Y])

If you want to change the spacing, you can play with the locations of the NaN's.

enter image description here

Upvotes: 1

yuk
yuk

Reputation: 19880

Something like this?

X=[1.1 1.4 1.2 1.1];
Y=[1.4 1.4 1.1];
a = [2 11] - 1;

bar((1:numel(X))+a(1), X, 'b')
hold on
bar((1:numel(Y))+a(2), Y, 'r')
hold off
set(gca,'XTickMode','auto')
legend({'X','Y'})

Upvotes: 2

Related Questions