Legend according to colours of the bars
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Man Shiu Kwok
le 13 Mar 2024
Réponse apportée : Walter Roberson
le 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 commentaires
Réponse acceptée
Walter Roberson
le 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Legend dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!