Hi, I have a vector x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] and corresponding y=[1 2 3 1 1 1 2 3 3 1 3 3 3 2 3]. I should generate a bar plot {bar(x,y)} such that bar corresponding to different numbers are in different colors. For example: Bar color corresponding to 1's should be red, Bar color for all 2's should be yellow and so on....Can someone please help with this?

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2016년 3월 29일

0 개 추천

x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
y=[1 2 3 1 1 1 2 3 3 1 3 3 3 2 3]
cl='rgyb'
for k=1:numel(x)
bar(x(k),y(k),'FaceColor' ,cl(y(k)))
hold on
end

댓글 수: 3

Sowmya MR
Sowmya MR 2016년 3월 29일
Thank you. This works. Also is there a way to display the corresponding values of y on top of the bar?
Nice! Or a more generalized form in case y = y+5;
x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] ;
y=[1 2 3 1 1 1 2 3 3 1 3 3 3 2 3];
uniquey = unique(y);
Ncolors = length(uniquey);
hold on
cmap = jet(Ncolors);
for k = 1:length(x)
bar(x(k),y(y(k)),'facecolor',cmap(uniquey==y(k),:))
end
Sowmya- To get the text labels put this at the end:
text(x,y,num2str(y'),'horiz','center','vert','bottom')
box off

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Chad Greene
Chad Greene 2016년 3월 29일
편집: Chad Greene 2016년 3월 29일

0 개 추천

You can set the facecolor of bar(s) when you call the bar function. Below I'm defining the rgb values of 15 colors with jet. The display is colorful, but perhaps not the most elegant design for data display. Fewer colors is usually better.
x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] ;
y=[1 2 3 1 1 1 2 3 3 1 3 3 3 2 3];
hold on
cmap = jet(length(x));
for k = 1:length(x)
bar(x(x==x(k)),y(x==x(k)),'facecolor',cmap(k,:))
end

카테고리

도움말 센터File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

질문:

2016년 3월 29일

댓글:

2016년 3월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by