Legend according to colours of the bars

조회 수: 2 (최근 30일)
Man Shiu Kwok
Man Shiu Kwok 2024년 3월 13일
답변: Walter Roberson 2024년 3월 14일
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

채택된 답변

Walter Roberson
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개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by