Reputation: 158
I am building a MATLAB script to add two markers for a single label similar to below in Python.
Does anyone know a way to modify the legend in MATLAB to include two markers adjacent to a common label?
Thanks
Upvotes: 0
Views: 425
Reputation: 6863
Slightly modifying the post here, you can get what you want. Note that this uses undocumented features, but it still works in R2021a.
figure; hold all; % new fig, enable hold/add
x=0:0.25:2*pi;
y=sin(x);
hL(1)=plot(x,y,'x','MarkerSize',10);
hL(2)=plot(x,y,'-','color',[1 0 0]);
% Add legend for the first/main plot handle
hLegend = legend(hL(1),'location','best');
drawnow(); % have to render the internal nodes before accessing them
% Extract legend nodes/primitives
hLegendEntry = hLegend.EntryContainer.NodeChildren(1); % first/bottom row of legend
iconSet = hLegendEntry.Icon.Transform.Children.Children; % array of first/bottom row's icons (marker+line)
% move the first icon to the left
LegendIcon1 = iconSet(1);
LegendIcon1.VertexData(1) = 0.2;
% Create a new icon marker to add to the icon set
LegendIcon2 = copy(iconSet(1)); % copy the object (or look into making a matlab.graphics.primitive.world.Marker)
LegendIcon2.get % list all properties
LegendIcon2.Parent = iconSet(1).Parent; % set the parent, adding to the legend's icon draw set
% Mess with the new icon's properties to show how you want
LegendIcon2.Style = 'hbar';
LegendIcon2.FaceColorData = uint8([255;0;0;0]); % rgba uint8
LegendIcon2.EdgeColorData = uint8([255;0;0;0]); % rgba uint8
LegendIcon2.VertexData(1) = 0.6; % [0-1] within the icon's boundaries (not the +0.02)
% newLegendIcon.VertexData(2) = 0.5; % [0-1] within the icon's boundaries (not the +0.02)
LegendIcon2.Size = 10; % a little different from MarkerSize it seems
Upvotes: 1