필터 지우기
필터 지우기

Why isn't my color assignment working in this bar graph?

조회 수: 6 (최근 30일)
Shannon
Shannon 2013년 11월 13일
댓글: Image Analyst 2013년 11월 14일
Hi all, I am trying to assign colors to individual bars in a bar plot that I'm making. I was able to do this before using a 3x3 matrix, but now with the 1x3 matrix (called "Slopes" below) I keep getting the error, "??? Index exceeds matrix dimensions. Error in ==> NColdthree at 93 set(bar1(2),'FaceColor','r')" when I try to run the following script:
Slopes = [-0.002 0.010 -0.012];
subplot(1,3,2) bar1 = bar(Slopes);
%Set the colors of the three bars set(bar1(1),'FaceColor','b') set(bar1(2),'FaceColor','r') set(bar1(3),'FaceColor','g')
%Add legend, axis labels, etc. legend(bar1,'P','E','P-E') ylabel 'Regression Coefficients' xlabel('Northern Cold*') title('Linear Trend','FontSize',16) axis([0 4 -0.05 0.05])
Any thoughts on why I can't specify the colors for the 2nd and 3rd bars? Thanks!

답변 (2개)

Image Analyst
Image Analyst 2013년 11월 13일
See attached demo.
  댓글 수: 4
Shannon
Shannon 2013년 11월 14일
Great, thank you for the clarification.
Image Analyst
Image Analyst 2013년 11월 14일
It sounds like, from your comment to vivek (who's code is the same as mine just with different variable names), that you got it working. If so, please mark my Answer as Accepted, otherwise let's get it figured out.

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


Vivek Selvam
Vivek Selvam 2013년 11월 13일
편집: Vivek Selvam 2013년 11월 13일
This link says how to. Hope the following illustration helps.
Slopes = [-0.002 0.010 -0.012];
numBars = numel(Slopes);
x = 1:numBars;
colStr = 'rgbymc';
for i = 1:numBars
barHan = bar(x(i),Slopes(i));
set(barHan,'FaceColor',colStr(i));
hold on
end
In case you have a lot of bars (therefore need more colors), you can make use of colormaps ( doc colormap ). For example using jet colormap (replace the corresponding lines in the above code):
colStr = jet(numBars); % line 4
set(barHan,'FaceColor',colStr(i,:)); % line 7

카테고리

Help CenterFile Exchange에서 Graphics Object Properties에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by