gabboshow
gabboshow

Reputation: 5569

position bars grouped bar plot matlab

In the following plot

y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
bar(y)

enter image description here

How can I retrieve the position of each bar in order to super impose a marker?

for example I would like to put a star on top of the 2nd (2nd bar of first group) and 5th (2nd bar of second group) bars.

I would prefer a solution that allows me to modify the plot once created.. (given the fig.) Thanks

Upvotes: 4

Views: 2137

Answers (1)

Ali Mirzaei
Ali Mirzaei

Reputation: 1552

You can use Xdata and Ydata to do this :

y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
h=bar(y);

% getting xdata and ydata from second bar in each group
xdata= get (h(2),'XData');
ydata= get (h(2),'YData');

% plot a * on second bar from second group
hold on;
offset=0.25;
plot(xdata(2),ydata(2)+offset,'-*');

enter image description here

If you want to mark a bar in center of group, this method works but if you wanted to mark for example a first one of one group you have to adjust the position of the * with a offset value in x axis.

for example I want to mark the third bar of second group :

y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
h=bar(y);

% getting xdata and ydata from second bar in each group
xdata= get (h(3),'XData');
ydata= get (h(3),'YData');

% plot a * on second bar from second group
hold on;
offset=0.25;
xoffset = 0.23; % manual set of get from properties of bar handle
plot(xdata(2)+xoffset,ydata(2)+offset,'-*');

enter image description here

Upvotes: 1

Related Questions