0

I am building a MATLAB script to add two markers for a single label similar to below in Python.

  1. How to create two legend objects for a single plot instance? and
  2. Sharing the same label for two plots with line and point markers in legend

Does anyone know a way to modify the legend in MATLAB to include two markers adjacent to a common label?

Thanks

2
  • see this post: mathworks.com/matlabcentral/answers/…
    – rinkert
    Commented Apr 6, 2022 at 9:09
  • Thanks @rinkert, but the script here combines two markers on top of each other. Instead, I want to display them next to each other with a single label.
    – techenthu
    Commented Apr 6, 2022 at 9:53

1 Answer 1

1

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

enter image description here

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.