Legend according to colours of the bars

3 ビュー (過去 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 Center および File ExchangeLegend についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by