Clear Filters
Clear Filters

2 Problems with creating a bar plot and a legend inside a for loop

1 view (last 30 days)
I have a set of data with which i am creating different plots and a bar plot in one diagram. All this happens in a for loop. I have created a cell array with different color codes so that each set of data has its own color. I first plotted 5 graphs in each loop which means 10 graph in total and everything worked well. But when i tried to create a bar plot and create a legend to my plots i run into the same problem. My legend and my bar just get the colors of my last loop/graph and one for every loop.
number = numel(s.DATA.X);
for i = 1:number
c = {'b','r','g','y','k'};
.
.
  1. Problem: Each loop calculates the gradient of a linear regression. I want to plot the gradients in a bar plot and each bar should have the color of its corresponding dataset. When plotting the linear regression inside my graph every one of them has a different color, like i want to. At the end when i try to plot a bar diagram (still inside the for loop) for some reason it doesnt work anymore and each bar has the same color.
p{i} = polyfit(x_relevant{i}, y_relevant{i},1);
fit{i} = polyval(p{i},x_relevant{i});
p3{i} = plot(x_relevant{i},fit{i},'color',c{i},'LineWidth',3); <--- Works fine
coefs = cell2mat(p(:));
subplot(4,1,4);
b = bar(coefs(:,1));
set(b,'FaceColor',c{i}); <--- Doesnt work, and puts all bars in the color of the last loop/graph
2. Problem: I am creating 5 plots in each loop which consists of the data split into 3 parts, a linear regression and a fit error. I want to creat a legend which has all 5 graphs for each loop and the right color, which would result in 10 rows in my legend witht he first 5 beeing blue and the second 5 beeing red. I only get 5 in total though.
p1{i} = plot(x_irrelevant1{i},y_irrelevant1{i},'color',[0.5 0.5 0.5],'Marker','.','linestyle','none');
hold on
p2{i} = plot(x_relevant{i},y_relevant{i},'color',c{i},'Marker','.','linestyle','none');
hold on
...
legend([p1{i},p2{i},p3{i},p4{i},p5{i}],'All Datapoints Set 1','Datapoints Set 1','Lin reg Set 1','Fitt Err','Fit Err2');

Accepted Answer

Patrick Petre
Patrick Petre on 30 Nov 2020
Edited: Patrick Petre on 30 Nov 2020
Okay so i figured out my problem number 2. Solution was to create a list with the legend names and + the variable and then to put each of them into the plot itself (...,'Displayname',legendname)

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!