how to write the legend in bar chart

how to add legend for the first, second and third column?
this is the code:
y =[44,55,54] ;
b = bar(y,0.5);
bar(y)

 Accepted Answer

Ameer Hamza
Ameer Hamza on 3 May 2020
Edited: Ameer Hamza on 3 May 2020
Try this
y =[44,55,54];
hold on
for i=1:numel(y)
bar(i, y(i))
end
legend({'first', 'second', 'third'})

14 Comments

do you know how to write names instead of numbers
first one: A
second: B
third: C
On the x-axis?
Run this
y =[44,55,54];
hold on
for i=1:numel(y)
bar(i, y(i))
end
xticks(1:numel(y))
xticklabels({'A', 'B', 'C'})
legend({'first', 'second', 'third'})
appreciate it mr Hamza thank you so much
I am glad to be of help.
oh! it's my mistake now i remember it's for y axis not x!
how would it be changed
Something like this
y =[44,55,54];
hold on
for i=1:numel(y)
bar(i, y(i))
end
[y_, idx] = sort(y);
labels = {'A', 'B', 'C'};
yticks(y_)
yticklabels(labels(idx))
legend({'first', 'second', 'third'})
thank you ive last question if you can help on it
why y =[44,55,54]; isn't shown, i mean i think it's not on y axis...
y =[44,55,54];
this data i want it in x axis but how can i run it in x axis?
You can replace A, B and C with what you want
y =[44,55,54];
hold on
for i=1:numel(y)
bar(i, y(i))
end
xticks(1:numel(y))
xticklabels({'44', '55', '54'})
legend({'first', 'second', 'third'})
thank you sir it worked thank you!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!