How do I colour different segments of a bar within a bar graph different colours (red or green) depending on if data has reached a threshold value
1 view (last 30 days)
Show older comments
Im trying to get a bar graph with force on y axis and weight on x axis. However, I want each bar to have segments of red and green depending on whether a threshold value has been met for positional data that was also recorded. How would this be done
% Create bar graph
figure;
hold on;
for i = 1:length(weights)
weight = weights{i};
force_vals = force_data{i};
zcom_vals = zcom_data{i};
for j = 1:length(force_vals)
force = force_vals(j);
zcom = zcom_vals(j);
if zcom > zcom_threshold
bar(i, force, 'FaceColor', 'g');
else
bar(i, force, 'FaceColor', 'r');
end
end
end
I can attach or explain any other code or data that may help if it is needed.
Thanks in advance.
1 Comment
dpb
on 5 Apr 2023
Knowing the precise content of the cell arrays would help, indeed. Attaching small sample dataset always helps folks actually do something specifically addressing the problem. As is, there's somewhat of a dilemma figuring out what you want -- whether the code is working as intended other than colors or what. Specifically, there are going to be length(weights)*length(force_vals) separate bars drawn with the nest loops but each is plotted only at the position of the outer loop? How many bars are there supposed to be, total?
If I understand the desire correctly, there would apparently would be only #weights bars, but each would consist of two segments, the section below the threshold and any above in red? It would seem that zcom_threshold is a constant, in which case that level will be the same for all? If this is the case and it is N bars with two segments each, the use the 'stacked' option where the input array to bar() will be a 2-row array of #weights columns; the bottom row the threshold value (constant) and the top the difference between the force and the threshold. But, this is an (how educated, I'm not sure) guess only...
Answers (1)
Mathieu NOE
on 6 Apr 2023
hello
maybe this ? (simple demo)
% stacked plot with threshold (lower => green, above th => red)
weigths = (1:10);
force = 2+weigths;
force_threshold = 6;
y = zeros(2,numel(force));
a = min(force,force_threshold); % force below or equal to force_threshold
b = force - a; % remaining portion above force_threshold
y = [a;b]; % stack both arrays
h = bar(y', 'stacked');
set(h,{'FaceColor'},{'g';'r'});
xlabel('Weights')
ylabel('Force')
3 Comments
Mathieu NOE
on 7 Apr 2023
hello @dpb
thanks for the nice comments
I admit I didn't pay too much attention to some details in the original post as , as you, I coudn't figure out how the whole thing was supposed to work
so I opted for what I thought was a simple but close enough valuable answer
all the best
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!