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

13 visualizaciones (últimos 30 días)
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

Respuestas (1)

Bearli Ubuku
Bearli Ubuku el 26 de Jul. de 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 comentario
Julian Thompson
Julian Thompson el 26 de Ag. de 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?

Iniciar sesión para comentar.

Categorías

Más información sobre Annotations en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by