It is relatively simple to add basic modifications to markers in matlab legends. The legend produced by the following code snippet ():
hold on
h = plot(inf,inf,'ob',inf,inf,'r+');
legend(h,'Data1','Data2');
Can be easily modified to: using the following code:
[~,~,icons,~] = legend(h,'Data1','Data2');
set(icons(1),'LineStyle','-')
set(icons(2),'LineStyle','-')
However things become fairly complicated if I want to correctly legend objects such as (circle is not in the middle of a line) or (several colors for one line with '+' markers on it). I have not found any property or workaround that allows to modify the position of the markers in the legend box, or add several markers in one legend group.
Does anyone know of a document that contains advanced information for legend customization? Or how to better use the numerous properties of graphic objects provided by matlab to achieve what is described above?
In the MatLab version up to
R2014a
thelegend
box is actually anaxes
so it is relatively easy to modify its content through its handle.From version
R2014b
thelegend
is agraphics object
and seems there is no way to access to the axes handle (ref. to this post on undocumentedmatlab).Up to R2014a
Given the legend for two lines in a plot:
if you want to move the
marker
on the first line to, for example, the end of the line, you can:XData
of the line (stored inb(3)
): it is an (1x2) arrayXData
of themarker
(stored inb(4)
) to the last value of the array obtained on the above stepIf you want to add more
marker
and have the second line made of more segments with different colours, you can:XData
andYData
of the line (stored inb(5)
)x coord
by splitting theXData
arrayfor
loop using theYData
value asy coord
This approach has been implemented in the following code in which, the legend box has been also enlarged to make in more "readable".
The comments in the code should explain the different steps.
This is the result:
From R2014b
Since it seems not possible to access to the legend axex, a solution could be(as suggested in the above mentoined post to add an
axes
and superimpose it to the legend.You could firt create the legend:
matlab.graphics.illustration.Legend
(tryclass(a)
)matlab.graphics.primitive.Data
objects (tryclass(b)
)in a similar way to the older versions, the
b
refers to:You can get the
position
andsize
of thelegend
through thelegend
objecta
.You can then apply the same approach described above in order to plot the "updated" legend.
This approach has been implemented in the following code (the comments should explains the different steps).
Hope this helps.
Qapla'