Legends in MATLAB®

How to modify the legend in MATLAB® graphs. Seven examples of how to move, color, and hide the legend.


fig = figure;
plot([1 2 3 4 5 6 7 8],[1 2 5 6 3 3 2 5]);
hold on
plot([1 2 3 4 5 6 7 8],[1 6 2 3 4 7 7 8]);
legend('blue trace','orange trace');

fig2plotly(fig);
fig = figure;
plot([1 2 3 4 5 6 7 8],[1 2 5 6 3 3 2 5]);
hold on
plot([1 2 3 4 5 6 7 8],[1 6 2 3 4 3 7 8]);
legend('blue trace','orange trace','Location','BestOutside');

fig2plotly(fig);
trace1 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 3, 6, 4, 5, 2, 3, 5, 4], ...
  'type', 'scatter');

trace2 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 4, 7, 8, 3, 6, 3, 3, 4], ...
  'type', 'scatter');

data = {trace1, trace2};

layout = struct('showlegend', false);

plotly(data, struct('layout', layout));
trace1 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 3, 6, 4, 5, 2, 3, 5, 4], ...
  'name', 'Blue Trace', ...
  'type', 'scatter');

trace2 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 4, 7, 8, 3, 6, 3, 3, 4], ...
  'name', 'Orange Trace', ...
  'type', 'scatter');

data = {trace1, trace2};

plotly(data);
trace1 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 3, 6, 4, 5, 2, 3, 5, 4], ...
  'type', 'scatter');

trace2 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 4, 7, 8, 3, 6, 3, 3, 4], ...
  'type', 'scatter');

data = {trace1, trace2};

layout = struct(...
    'showlegend', true, ...
    'legend', struct(...
      'x', 1, ...
      'y', 1));

plotly(data, struct('layout', layout));
trace1 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 3, 6, 4, 5, 2, 3, 5, 4], ...
  'type', 'scatter');

trace2 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 4, 7, 8, 3, 6, 3, 3, 4], ...
  'type', 'scatter');

data = {trace1, trace2};

layout = struct(...
    'showlegend', true, ...
    'legend', struct(...
      'x', 100, ...
      'y', 1));

plotly(data, struct('layout', layout));
trace1 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 3, 6, 4, 5, 2, 3, 5, 4], ...
  'type', 'scatter');

trace2 = struct(...
  'x', [0, 1, 2, 3, 4, 5, 6, 7, 8], ...
  'y', [0, 4, 7, 8, 3, 6, 3, 3, 4], ...
  'type', 'scatter');

data = {trace1, trace2};

layout = struct('legend', struct(...
      'x', 0, ...
      'y', 1, ...
      'traceorder', 'normal', ...
      'font', struct(...
        'family', 'sans-serif', ...
        'size', 12, ...
        'color', '#000'), ...
      'bgcolor', '#E2E2E2', ...
      'bordercolor', '#FFFFFF', ...
      'borderwidth', 2));

plotly(data, struct('layout', layout));
trace1 = struct(...
  'x', [0, 1, 2], ...
  'y', [1, 2, 3], ...
  'name', 'First Trace', ...
  'showlegend', false, ...
  'type', 'scatter');

trace2 = struct(...
  'x', [0, 1, 2, 3], ...
  'y', [8, 4, 2, 0], ...
  'name', 'Second Trace', ...
  'showlegend', true, ...
  'type', 'scatter');

data = {trace1, trace2};

plotly(data);