Legend according to colours of the bars
3 views (last 30 days)
Show older comments
Man Shiu Kwok
on 13 Mar 2024
Answered: Walter Roberson
on 14 Mar 2024
I am trying to plot the values of items coming from multiple questionnaires. I successfully color-coded the bars according to which questionnaire the item belongs to, however, I am struggling to add a legend that can corresponds to the colour labelling. I tried using legend(), but it keeps telling me "Warning: Ignoring extra legend entries" and gave me only the first legend entry correctly (see screenshot)
arrays stores the name of the datasets I am looping through. The 2nd column of each array is the value i am plotting and 7th column of the array indicates which questionnaire the item is from (1-6).
questionnaire = {'A', 'B', 'C', 'D', 'E', 'F'};
for i = 1:numel(arrays)
subplot(4, 1, i);
values = arrays{i}(:, 2);
b= bar(values,'FaceColor','flat');
cmap = getColor(arrays{i}(:, 7));
b.CData= cmap;
yline(.3)
yline(-.3)
b= legend(questionnaire,'Location','northeastoutside');
end
function color = getColor(values)
% Define colors based on the values in column 7
unique_values = unique(values);
num_unique = numel(unique_values);
colormap_lines = lines(num_unique);
[~, index] = ismember(values, unique_values);
color = colormap_lines(index, :);
end
0 Comments
Accepted Answer
Walter Roberson
on 14 Mar 2024
questionnaire = {'A', 'B', 'C', 'D', 'E', 'F'};
for i = 1:numel(arrays)
subplot(4, 1, i);
values = arrays{i}(:, 2);
b = bar(values,'FaceColor','flat');
cmap = getColor(arrays{i}(:, 7));
b.CData= cmap;
yline(.3)
yline(-.3)
H = gobjects(numel(questionnaire),1);
for K = 1 : numel(questionnaire);
H(K) = line(nan, nan, 'DisplayName', questionnaire{K}, 'Color', cmap(K,:));
end
legend(H,'Location','northeastoutside');
end
function color = getColor(values)
% Define colors based on the values in column 7
unique_values = unique(values);
num_unique = numel(unique_values);
colormap_lines = lines(num_unique);
[~, index] = ismember(values, unique_values);
color = colormap_lines(index, :);
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!