legend showing wrong colours

13 visualizaciones (últimos 30 días)
Robin Strak
Robin Strak el 17 de Mzo. de 2020
Comentada: Adam Danz el 18 de Mzo. de 2020
Hi,
I want to plot 4 different arrays and their corresponding trendlines. In order to discriminate between those 4 I want them to have their own colour. Unfortunately my legend doesn´t correspond to the plots (see attached screenshot) - it should only show "Graph A1", "Graph A2", "Graph A3" and Graph A4" with four different colours.
j = 1;
k = 1;
str = {'A1', 'A2', 'A3', 'A4'};
col = {'r', 'k', 'g', 'b'};
for i = 1:20:80
plot(M_3(i:19+i), col{k}, 'LineWidth',1);
str = [str ("Graph " + str(j))];
c_rms = polyfit(time,M_3(i:19+i),1);
y_est = polyval(c_rms,time);
hold on
plot(time,y_est, col{k}, 'LineWidth',2);
j = j+1;
k = k+1;
end
set(gcf,'position',[0 500 1000 300])
xlabel('time / min');
ylabel('electrical activity in % of the maximal force');
grid on; grid minor;
legend(str);
I would be very happy if you could help me out, maybe I just missordered the loop.
Thanks,
Robin

Respuesta aceptada

Adam Danz
Adam Danz el 17 de Mzo. de 2020
Editada: Adam Danz el 17 de Mzo. de 2020
The easiest way to manage legend text is by using the DisplayName property of graphics objects. Here's how that might look when plotting in a loop.
str = {'A1', 'A2', 'A3', 'A4'};
hold on
for i = 1:4
% . . . skipping stuff
plot(x,y,'DisplayName', str{i})
plot(xFit,yFit,'DisplayName', [str{i},' fit'])
end
legend()
If you only want some objects to appear in the legend,
str = {'A1', 'A2', 'A3', 'A4'};
hold on
handles = gobjects(4,1);
for i = 1:4
% . . . skipping stuff
handles(i) = plot(x,y,'DisplayName', str{i});
plot(xFit,yFit)
end
legend(handles)
  2 comentarios
Robin Strak
Robin Strak el 18 de Mzo. de 2020
Thanks for you quick answer, Adam!
I tried to incorporate your tip, but in my case there still a little bug:
As I want to plot M_3 in 4 parts I looped it with for j = 1:20:80, so in order to choose the displayed string (A1,A2, ...) I need another loop - as you descriped.
time = linspace(0,22,20);
str = {'A1', 'A2', 'A3', 'A4'};
hold on
for i = 1:4
for j = 1:20:80
plot(time, M_3(i:19+i),'DisplayName', str{i})
j = j+1;
end
end
legend()
I´ve tried that but now I´ve got 16 graphs plotted. Do you think I could solve it with only one loop?
Thanks,
Robin
Adam Danz
Adam Danz el 18 de Mzo. de 2020
Instead of setting up your loop like this
for i = 1:20:80
plot(M_3(i:19+i), . . .);
. . .
end
set it up like this
vec = 1:20:80;
for i = 1:numel(vec)
plot(M_3(vec(i):19+vec(i)), . . .);
% ^^^^^^ ^^^^^^
. . .
end
That way your loop uses integer values 1:n that can be used as indices.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Graphics Performance en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by