Is it possible to get MATLAB to automatically associate legend icon colors with the applicable data?

1 次查看(过去 30 天)
I’m attempting to hard code colors to data in a 2D plot using the following code;
% Clear out all variables from the Workspace and the Command Window
clear all;
clc;
% Variables for plotting
To_Time = 58560;
Time_Tag = [58568.4; 58571.8; 58573.4; 58574.4; 58577.4; 58579.8; 58582.4; 58584.1; 58587.6; 58589];
ID = [10; 2; 3; 4; 10; 6; 7; 2; 10; 2];
Measured_Data = [1.25; 2.31; 3.3; 4.9; 5.7; 6.7; 7.1; 8.6; 9.1; 10];
% Calculate TALO times for all IDs
TALO_Time = Time_Tag - To_Time;
% Preallocate
LegCol = cell(1, size(ID, 1));
color = cell(1, size(ID, 1));
% Setup cases for auto legend generation
for idx = 1:size(ID, 1)
switch ID(idx)
case 1
LegCol{idx} = 'Data-1';
color{idx} = [1 0 0]; % red
case 2
LegCol{idx} = 'Data-2';
color{idx} = [0 1 0]; % green
case 3
LegCol{idx} = 'Data-3';
color{idx} = [0 0 1]; % blue
case 4
LegCol{idx} = 'Data-4';
color{idx} = [1 0.55 0]; % orange
case 5
LegCol{idx} = 'Data-5';
color{idx} = [1 0 1]; % magenta
case 6
LegCol{idx} = 'Data-6';
color{idx} = [0 1 1]; % cyan
case 7
LegCol{idx} = 'Data-7';
color{idx} = [0 0 0]; % black
case 8
LegCol{idx} = 'Data-8';
color{idx} = [1 1 0]; % yellow
case 9
LegCol{idx} = 'Data-9';
color{idx} = [0.58 0 0.83]; % violet
case 10
LegCol{idx} = 'Data-10';
color{idx} = [0.72 0.53 0.04]; % gold
end
% Transpode LegCol and color data for legend use
Legend_Nomenclature = transpose(LegCol);
New_Colors = transpose(color);
% Setup the TALO Plot
h = plot(TALO_Time(idx), Measured_Data(idx), 'o', 'Color', New_Colors{idx}, 'MarkerSize', 14);
set(h, 'MarkerFaceColor', New_Colors{idx});
hold all;
end
AA = unique(Legend_Nomenclature);
hleg = legend(AA, 'Location', 'NortheastOutside');
The following plot is produced;
While the plotted data is correct, the corresponding legend icon colors are not. I’m getting;
Gold Data-10
Green Data-2
Blue Data-3
Orange Data-4
Gold Data-6 (should be cyan)
Cyan Data-7 (should be black)
Is there a way to automatically associate legend icon colors with the applicable data?
Thank you.

采纳的回答

Sean de Wolski
Sean de Wolski 2015-1-23
Legend has the ability to pass in specific line objects to be legend-ized. Here, you throw away those lines in the for-loop. Instead, store them and legend-ize the applicable unique ones from AA:
% <snip>
% Store h(idx), set(h(idx),...
h(idx) = plot(TALO_Time(idx), Measured_Data(idx), 'o', 'Color', New_Colors{idx}, 'MarkerSize', 14);
set(h(idx), 'MarkerFaceColor', New_Colors{idx});
hold all;
end
%%Grab unique sources and legend
[AA,idxu] = unique(Legend_Nomenclature);
hleg = legend(h(idxu),AA, 'Location', 'NortheastOutside');

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by