I'm creating a plot in matlab that includes some lines, as well as a fill. For example,
fill([0 1 1], [0 1 0], [.9 .9 .9]);
plot(rand(5, 开发者_JAVA百科1), 'b');
plot(rand(5, 1), 'r');
plot(rand(5, 1), 'g');
legend('fill', 'line one', 'line two', 'line three');
I can change the length of the sample lines in the legend with:
f = findobj('type', 'line');
set(f(2), 'XData', [.2, .3]); % Changes line three
set(f(4), 'XData', [.2, .3]); % Changes line two
set(f(6), 'XData', [.2, .3]); % Changes line one
But this method doesn't seem to work for the fill. How do I change the size of the fill sample in the legend?
fill([0 1 1], [0 1 0], [.9 .9 .9]); hold on
plot(rand(5, 1), 'b');
plot(rand(5, 1), 'r');
plot(rand(5, 1), 'g'); hold off
h = legend('fill', 'line one', 'line two', 'line three');
%# find handles of lines inside legend that have a non-empty tag
hLegendLines = findobj(h, 'type', 'line', '-and', '-regexp','Tag','[^'']');
set(hLegendLines, 'XData', [.2, .3])
%# find handle of patch inside legend
hLegendPatch = findobj(h, 'type', 'patch');
set(hLegendPatch, 'XData', [.2, .2, .3, .3])
EDIT: (response to comments)
You can manipulating the size of the legend by setting the Position
property. However, it seems that the legend fits its content as tight as possible by default, so you can make it bigger, but not smaller (try resizing it with the mouse):
p = get(h,'Position'); p(3)=0.1;
set(h, 'Position',p);
Another way is to reduce the font size used for the labels:
h = legend('fill', 'line one', 'line two', 'line three')
set(h, 'FontSize',6); %# do this before changing the other stuff
As of MATLAB R2014b and upwards (the new graphics engine "HG2") legends are implemented differently and the graphics objects found using the original answer no longer exist.
It looks like the "previews" are now LegendIcon
objects that are accessible as the Icon
property of the LegendEntry
object for each entry in the legend. The LegendEntry
objects are stashed away as children of a hidden property of the Legend
object called EntryContainer
.
The LegendIcon
objects have a Transform
property which appears to have control of the size of the item in them. To reduce the width, change the first element of the Matrix
property, which defines the x-axis scaling of the transformation.
To make all entries half as wide, for example, this looks something like the following:
hLegend = findobj('Type','legend');
entries = hLegend.EntryContainer.Children;
for entry = entries(:)'
T = entry.Icon.Transform;
T.Matrix(1) = T.Matrix(1) / 2;
end
Note that as previously, this doesn't make the legend itself narrower. If you try to resize the legend after changing the icon transformations, even to make the legend bigger, the transform seems to reset.
精彩评论