Changing each bar in a plot a specific color

2 次查看(过去 30 天)
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 个评论
Patrick Petre
Patrick Petre 2020-11-29
Doesnt work.
coefs = cell2mat(p(:));
subplot(4,1,4);
b1 = bar(coefs(:,1));
b2 = bar(coefs(:,2));
%set(b,'FaceColor',c{i});
set(b1,'FaceColor',c{1});
set(b2,'FaceColor',c{2});
Error using matlab.graphics.chart.primitive.Bar/set
Invalid or deleted object.
Error in Tyre_plots_try10 (line 98)
set(b1,'FaceColor',c{1});
VBBV
VBBV 2020-11-29
%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

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by