manipulating plot legend, assigning colours
5 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I have complex data which I want to plot. My code is:
if true
% code
end
for bb = 1:size(Data.Measured,2)
%calculating how many measurements we have for right and left ear
idx1 = strfind(Data.Side, 'Right');
idx1 = find(not(cellfun('isempty',idx1)));
N (bb) = length(idx1);
idx2 = strfind(Data.Side, 'Left');
idx2 = find(not(cellfun('isempty',idx2))) ;
M (bb) = length(idx2) ;
for kk = 1:size(Data.Name,2)
if strcmpi(Data.Side{kk}, 'Right')
subplot(2,1,1)
Data.legend.sub1{c1} = regexprep(Data.Name{kk},'_',' ');
c1 = c1+1;
legend(Data.legend.sub1(1:N))
title([name(bb),' Right'])
else
subplot(2,1,2)
title([name(bb),' Left'])
Data.legend.sub2{c2} = regexprep(Data.Name{kk},'_',' ');
c2 = c2+1;
legend(Data.legend.sub2(N+1:N+M))
end
end
the problem I have here is that my Data.legend.sub1 and Data.legend.sub2 give me all measurements done for all subjects but in reverse order:
Data.legend.sub1
Data.legend.sub2
Thus, my legend is using different colours for different measurements. First, I want to make sure that I am only plotting measurements for right side (is it already ensured by line :if strcmpi(Data.Side{kk}, 'Right')?). second I want to use the same colours for the same measurement for both sides. third, I am not sure why I am getting warning 'Ignoring extra legend entries.' and then one measurement is always omitted in the legend and specified just as 'data 1'...
I hope my explanation is clear.
8 件のコメント
Adam
2018 年 10 月 16 日
The colours in the legend should still reflect the colours of the lines though otherwise what is the point of the legend?
採用された回答
jonas
2018 年 10 月 16 日
編集済み: jonas
2018 年 10 月 16 日
Always output the plot handle.
h = plot(...)
If you are plotting in a loop, then save all handles.
h(i) = plot(...)
You can add the legend outside of your loop, by passing all the handles (in the desired order) and a cell array of legend entries.
legend(h,{leg1,leg2,leg3})
or perhaps you want them in reversed order
legend(flipud(h),{leg1,leg2,leg3})
Another alternative would be to pass the legend entry directly to your plot.
plot(...,'displayname',legn)
and then simply pass the handles to the legend
legend(h)
If you use any of the above methods, you should never again run into the warning 'ignoring extra legend entries'. Just make sure that the size of your cell array with legend entries matches the size of the array with handles.
5 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Legend についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!