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

18 Ansichten (letzte 30 Tage)
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

Antworten (1)

Bearli Ubuku
Bearli Ubuku am 26 Jul. 2013
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 Kommentar
Julian Thompson
Julian Thompson am 26 Aug. 2016
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?

Melden Sie sich an, um zu kommentieren.

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by