How to bar plot legend with group by color ?
3 views (last 30 days)
Show older comments
Ninlawat Phuangchoke
on 14 Nov 2020
Commented: Ameer Hamza
on 14 Nov 2020
Hi all ,I want plot bar graph and show legend with group by color.but now I not sure which I mistake.
when I use command "legend()" The result is as shown in the picture.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/413693/image.jpeg)
## Bar plot
T4 = DAtavi.Turbidity;
y4 = month(DAtavi.Date);
[Uy4,~,Ix] = unique(y4);
T4Max = accumarray(Ix, T4, [], @max);
bar(Uy4, T4Max)
name = {'Jan';'Feb';'Mar';'Apr';'May';'Jun';'Jul';'Aug';'Sep';'Oct';'Nov';'Dec'};
set(gca,'XTick',1:12,'xticklabel',name);
grid on;
hold on;
# Set color
set(bar(Uy4(1), T4Max(1)),'FaceColor','g');
set(bar(Uy4(2), T4Max(2)),'FaceColor','g');
set(bar(Uy4(3), T4Max(3)),'FaceColor','r');
set(bar(Uy4(4), T4Max(4)),'FaceColor','r');
set(bar(Uy4(5), T4Max(5)),'FaceColor','r');
set(bar(Uy4(6), T4Max(6)),'FaceColor','r');
set(bar(Uy4(7), T4Max(7)),'FaceColor','b');
set(bar(Uy4(8), T4Max(8)),'FaceColor','b');
set(bar(Uy4(9), T4Max(9)),'FaceColor','b');
set(bar(Uy4(10), T4Max(10)),'FaceColor','b');
set(bar(Uy4(11), T4Max(11)),'FaceColor','g');
set(bar(Uy4(12), T4Max(12)),'FaceColor','g');
legend()
0 Comments
Accepted Answer
Ameer Hamza
on 14 Nov 2020
Here is a crude way to solve this problem
T4 = DAtavi.Turbidity;
y4 = month(DAtavi.Date);
[Uy4,~,Ix] = unique(y4);
T4Max = accumarray(Ix, T4, [], @max);
name = {'Jan';'Feb';'Mar';'Apr';'May';'Jun';'Jul';'Aug';'Sep';'Oct';'Nov';'Dec'};
ax = axes();
grid on;
hold on;
hb1 = bar(Uy4(1), T4Max(1), 'FaceColor','g');
bar(Uy4(2), T4Max(2), 'FaceColor','g')
hb2 = bar(Uy4(3), T4Max(3), 'FaceColor','r');
bar(Uy4(4), T4Max(4), 'FaceColor','r')
bar(Uy4(5), T4Max(5), 'FaceColor','r')
bar(Uy4(6), T4Max(6), 'FaceColor','r')
hb3 = bar(Uy4(7), T4Max(7) ,'FaceColor','b');
bar(Uy4(8), T4Max(8) ,'FaceColor','b')
bar(Uy4(9), T4Max(9) ,'FaceColor','b')
bar(Uy4(10), T4Max(10) ,'FaceColor','b')
hb4 = bar(Uy4(11), T4Max(11), 'FaceColor','g');
bar(Uy4(12), T4Max(12), 'FaceColor','g')
legend([hb1 hb2 hb3 hb4])
set(gca,'XTick',1:12,'xticklabel',name);
2 Comments
More Answers (0)
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!