Mallvina
Mallvina

Reputation: 213

How to add label or change the colour of certain bar in multiple bar plot

Lets say I have a multiple bar, which looks smth like that:

aa = repmat([1 2 10 5 15 3], 5,1)
aa =

     1     2    10     5    15     3
     1     2    10     5    15     3
     1     2    10     5    15     3
     1     2    10     5    15     3
     1     2    10     5    15     3

bar(aa)

enter image description here

What I need is to put a star or a label on some certain column, which sutisfies some conditions. Another option is to change the colour of that bar.

If I could get the coordinates of each column I could use plot. Or maybe I can modify errorbar somehow? Thanks for any advices.

Upvotes: 1

Views: 5467

Answers (2)

Gunther Struyf
Gunther Struyf

Reputation: 11168

Problem

You can get the x and y values of the bars (x=horizontal position, y=height of each bar) using:

hb=bar(aa);
x=cell2mat(get(hb,'Xdata'));
y=cell2mat(get(hb,'Ydata'));

which you can then use to plot a textlabel with text, or even just plot the mark symbols with plot:

plot(x,y,'*',Markersize',12)

Unfortunately, this only works correctly if you only have one single serie of data, because Xdata contains the index in the series (1,2,3,etc). For multiple series matlab spreads the bars around that index, but the Xdata values are all the same (despite in the plot, they aren't plotted at exact the same position).

Solution

Add the option 'hist' to the bar plotting:

hb=bar(aa,'hist')

this creates patches rather than barseries, and

x=cell2mat(get(hb,'Xdata'));
y=cell2mat(get(hb,'Ydata'));

now contains the (actual) corners of those patches. Extract the x-center as follows:

xcenter = 0.5*(x(2:4:end,:)+x(3:4:end,:));

The height is obtainable with one of the upper corners of the patch:

ytop = y(2:4:end,:);

Now you can use that for the plotting:

idx_mark = 3;
plot(xcenter(idx_mark ,:),ytop(idx_mark ,:),'*','Markersize',12)

enter image description here

or for annotation:

text(xcenter(idx_mark ,2),ytop(idx_mark ,2),'MARKED',...
    'HorizontalAlignment','center', ...
    'VerticalAlignment','bottom' )

enter image description here

Upvotes: 1

AdrienNK
AdrienNK

Reputation: 848

I think that what you could do that (for the colors) with playing a little with the bar function properties.

It also all depends if you know more or less how your plot will look like; if you know beforehand I think you could use XTick and XTicklabel to label you columns.

http://www.mathworks.nl/help/techdoc/ref/bar.html

Upvotes: 0

Related Questions