I am trying to give legend to the whole plot. I know it sounds easy for many cases. But it makes me puzzled in this particular case.
figure;
p1 = plot(1:3,[y1,y2,y3],1:2,y4,1:3,[y5,y6,y7,y8,y9])
% Add lines
hold on
h1 = line([1 2 3],[10 10 10]);
h2 = line([1 2 3],[100 100 100]);
% Set properties of lines
set([h1 h2],'LineStyle','none')
% Add a patch
p2 = patch([1 3 3 1],[10 10 100 100],[.85 .85 .85],'LineStyle','none','FaceAlpha',0.5,'DisplayName','Lab Measurement');
hold off
set(gca, 'children',flipud(get(gca,'children')),'XTickLabel', {'L1' ' ' ' ' ' ' ' ' 'L2' ' ' ' ' ' ' ' ' 'L3'},'YScale', 'log')
NameArray = {'Marker','Color','LineStyle','DisplayName'};
ValueArray = {'o','[0.2 0.2 0.2]','-','Var1';...
'+','[0.2 0.2 0.2]','-','Var2';...
'*','[0.2 0.2 0.2]','-','Var3';...
'.','[0.2 0.2 0.2]','-','Var4';...
'x','[0.2 0.2 0.2]','-','Var5';...
's','[0.2 0.2 0.2]','-','Var6';...
'd','[0.2 0.2 0.2]','-','Var7';...
'^','[0.2 0.2 0.2]',':','Var8';...
'h','[0.2 0.2 0.2]','-.','Var9'};
set(p1,NameArray,ValueArray)
When I tried to reveal the legend by giving
legend(p1)
or
legend(p2)
This is what looks like when I try legend(p2)
It just did fine for each part, but not together.
I also tried by giving the legend in command
legend([p2 p1],{'Lab Measurement','Var1','Var2','Var3','Var4','Var5','Var6','Var7','Var8','Var9'})
or
legend([p2 p1],{'Lab Measurement',{'Var1','Var2','Var3','Var4','Var5','Var6','Var7','Var8','Var9'}})
It did not work. Any help would be greatly appreciated!
Per the documentation for plot
:
h = plot(___)
returns a column vector of chart line objects.
When multiple plot pairs are provided, as in your case, the return from plot
is said array of objects:
>> a = plot(1, 2, 1, 2)
a =
2×1 Line array:
Line
Line
The bracket notation for concatenation []
generally implies the user wants to create a row vector, MATLAB does not make assumptions in the case of a vector and a scalar. This means it attempts to use horzcat
to concatenate the arrays, which, logically, throws an error.
>> b = plot(1, 2); c = [a b];
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
You'll need to explicitly tell MATLAB that you want to vertically concatenate these, or transpose the column vector into a row vector.
>> c = vertcat(a, b)
c =
3×1 Line array:
Line
Line
Line
or:
>> c = [a.' b]
c =
1×3 Line array:
Line Line Line
Both of which are compatible with legend
.
Yay.
Just use
p = vertcat(p2,p1);
legend(p)
Problem solved. Thanks!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.