Changing each bar in a plot a specific color
1 view (last 30 days)
Show older comments
I have a for Loop that with each loop create a plot and fit a linear regression to that plot. At the end i want to create a subplot as a bar diagramm that compares the gradient of the lin regression. With the following code it creates the bar diagram. My problem is that with each loop the plots have a specific color. The Bar diagram should fit that color so that the graph1 with the linear regression 1 and the bar1 all have the same color. In my loop it works to just reference to my c but with the bar diagram it doesnt work.
number = numel(data);
for i = 1:number
c = {'b','r','g','y','k'};
c2 = {[0.4;0.5;0.7],[0.8,0.4,0.5],[0.2,0.3,0,3],[1,0.9,0.7],[0.5,0.6,0.7]};
p{i} = polyfit(x_relevant{i}, y_relevant{i},1);
fit{i} = polyval(p{i},x_relevant{i})
p3 = plot(x_relevant{i},fit{i},'color',c{i},'LineWidth',3)
end
coefs = cell2mat(p(:));
subplot(4,1,4)
b = bar(coefs(:,1));
b.FaceColor = 'flat';
b.CData = c{i};
--->
Error setting property 'CData' of class 'Bar':
Value must be a scalar, vector or array of numeric type
if i change the last line to
b.CData = c2{i};
it semi works. The color changes but all bars have the same color(the one for c2{2}) which makes sense bc my i is 2 after the for loop but even if i put the bar plot inside my for loop it just is 2
8 Comments
VBBV
on 29 Nov 2020
%true
hold on
b1 = bar(coefs(:,1));
hold on
b2 = bar(coefs(:,2));
set(b1,'FaceColor',c{1});
set(b2,'FaceColor',c{2});
Try hold on btw bar plots
Answers (0)
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!