legend showing wrong colours
14 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Adam Danz
2020-3-17
编辑:Adam Danz
2020-3-17
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 个评论
Adam Danz
2020-3-18
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!