Changing each bar in a plot a specific color

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

VBBV
VBBV 2020년 11월 29일
What is the size of data? I.e. maximum value of number
VBBV
VBBV 2020년 11월 29일
Does plot figure inside for loop show different colors?
Patrick Petre
Patrick Petre 2020년 11월 29일
편집: Patrick Petre 2020년 11월 29일
In my example only2 but it should work for a different number aswell. Yes my Plots show different colors
Try some thing like below:
b = bar(coefs(:,1));
set(b,'FaceColor',c{i});
Already tried. Just puts both of my bars in the scond color. So while my plot1 is blue and my plot 2 is red, both of my bars are red.
hold on
b1 = bar(coefs(:,1));
b2 = bar(coefs(:,2));
set(b1,'FaceColor',c{1});
set(b2,'FaceColor',c{2});
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});
%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개)

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 11월 29일

댓글:

2020년 11월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by