Legend according to colours of the bars
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2024-3-14
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!