Change color of stacked bars according to values

Hello,
I am trying to plot a stacked bar chart, where each bar has a color shade depending on values from another vector. I tried to use CData but failed..
bin_width is the bar widths that made the stacked bar chart with.
However, the color shade of each bar should depend on the values in mtot. I'm having trouble creating a new colormap that can be applied on my bar chart.
%reading input
mtot=table(3,:); %this is an array of size (1 x 32), these are the values that should define the color of the bars
% %tried to set a new color bar
% caxis([min_m max_m]);
% colorbar
% hold on
%plotting of stacked bar chart
% barcolor=c(size(mtot,2));
f=barh(0,bin_width','stacked','FaceColor','flat');
set(gca,'XScale','log');

Answers (1)

Hi, Yasmin,
My understanding of your question is that you want to plot a horizontal stacked bar chart
with customized color for each bar. One way to achieve your goal is by setting 'FaceColor'
parameter for each bar using a for loop.
Here is an example, hope it is helpful.
load count.dat;
y = count(1:4,:); % y is a 4-by-3 matrix
width = 0.7;
colors = {'r', 'g', [0,0.5,0.5]}; % customized colors wrapped in a cell array, element could be either a color mark or a RGB vector
% set up colors
h = barh(y, width, 'stacked', 'LineStyle',':');
for i = 1 : 3
h(i).FaceColor = colors{i};
end
figure.jpg
For more information, please refer to barh function document.

3 Comments

Thanks but actually i want the color to reflect values from another input vector.
So bin_width has the variable to plot the stacked bar but mtot has the values of which i want to color the bars. so for example if the mtot(1,1) = 3 then the color should be red for example, but if its 8 then it should be green. The problem is i have 32-40 values of mtot for each day of the whole year, so i can't specifiy certain colors for specific values. I thought of breaking mtot into bins and assigning a color to each bin but failed to connect that in a way to be reflected on the bar colors that are plotted from bin_width.
Any ideas??
Xin Li
Xin Li on 19 Dec 2019
Edited: Xin Li on 19 Dec 2019
It is easy to generate a clolor map with function cool.
Say, if you want to have 40 colors, just do
colors = cool(40);
assume mtot(1,1) = 3, then colors(3, :) is the actual color for that bar.
Im sorry but can you clarify further. My problem is how to connect the values of mtot to colors that the bar takes accordingly. How do you write that in code?

Sign in to comment.

Products

Release

R2019b

Asked:

on 18 Dec 2019

Commented:

on 19 Dec 2019

Community Treasure Hunt

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

Start Hunting!