How do I define colors for individual bars on my STACKED bar graph according to their values

조회 수: 14 (최근 30일)
Hi all,
I'm trying to create a plot as shown in Plot 1. Depending on a value shown in plot 2, the color of the stacked bar (essentially boxes) should change.
After some research, I found the following solution on mathworks:
The trouble I'm having now is to adapt the problem to a stacked bar. To keep it simple, I first tried to just change the code from the mathworks solution for stacked charts:
mydata=rand(2,3); % here I added a 2nd row
bar_h=bar(mydata,'stack'); % here I added 'stack'
bar_child=get(bar_h,'Children');
set(bar_child,'CData',mydata);
mycolor=[0 0 0;0 0 1;1 0 0];
colormap(mycolor)
set(bar_child,'CDataMapping','direct');
for iCount=1:length(mydata)
if (mydata(iCount)<.2)
index(iCount)=1;
elseif(mydata(iCount)>=.6)
index(iCount)=3;
else
index(iCount)=2;
end
end
set(bar_child, 'CData',index);
colormap(mycolor);
The first problem arises at the line:
set(bar_child,'CData',mydata);
with the following error:
Error using set
Conversion to double from cell is not possible.
Can you please give me some help in adapting this solution for stacked bars?
Regards,
bearli

답변 (1개)

Bearli Ubuku
Bearli Ubuku 2013년 7월 26일
Hi, found myself the first answer of how to adapt the mathworks solution:
mydata=rand(3,2);
bar_h=bar(mydata,'stack');
mycolor=[0 0 0;0 0 1;1 0 0];
colormap(mycolor)
bar_child=cell2mat(get(bar_h,'Children'));
for i=1:size(bar_child,1)
set(bar_child(i),'CData',mydata(:,i));
set(bar_child(i),'CDataMapping','direct');
end
for i=1:size(bar_child,1)
for iCount=1:size(mydata,1)
if (mydata(iCount,i)<.2)
index(iCount,i)=1;
elseif(mydata(iCount,i)>=.6)
index(iCount,i)=3;
else
index(iCount,i)=2;
end
end
set(bar_child(i), 'CData',index(:,i)');
end
  댓글 수: 1
Julian Thompson
Julian Thompson 2016년 8월 26일
Hi, I am trying to do the same (I have Matlab 2015b) and get an error when I try the solution you found:
Error using cell2mat (line 52) CELL2MAT does not support cell arrays containing cell arrays or objects.
Error in Metric_change_0_or_1_mk4 (line 71) bar_child=cell2mat(get(bar_h,'Children'));
Any ideas?

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

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by