bar plot - add multiple y values for same x
2 views (last 30 days)
Show older comments
Hello,
I have an array A which contains some integer values, an array B which contains indices:
A = [ 1 2 3 4 5 6]
B = [3 1 2 1 2 1]
let's say that the maximal value at B can be 5 and some indices can also be blank.
I'd like to make a bar plot which will contain multiple bars where it's possible more than one value for the index:

How can it be done?
Thanks,
Avihai
0 Comments
Answers (1)
BhaTTa
on 29 May 2025
Hey @avihai, please refer to the below example code , please take it as a reference and modify it accordingly
A = [1 2 3 4 5 6];
B = [3 1 2 1 2 1];
% Define the maximum possible index value from B.
% If B could contain indices larger than 5, you'd use max(B) instead of a fixed 5.
max_b_value = 5;
% 1. Group the A values by their corresponding B indices
% We'll use a cell array to store values for each index, as they can have different counts.
grouped_data = cell(1, max_b_value);
for i = 1:length(A)
current_index = B(i);
current_value = A(i);
if current_index >= 1 && current_index <= max_b_value
grouped_data{current_index} = [grouped_data{current_index}, current_value];
else
warning('Index %d from B is out of the expected range (1 to %d). Skipping.', current_index, max_b_value);
end
end
% 2. Prepare the data for the bar plot
% The 'bar' function expects a matrix where each column represents an X-axis group
% and rows represent the different bars within that group.
% We need to pad shorter groups with NaN (Not a Number) so all columns have the same length.
% Find the maximum number of values for any single index
max_bars_per_index = 0;
for i = 1:max_b_value
max_bars_per_index = max(max_bars_per_index, length(grouped_data{i}));
end
plot_matrix = NaN(max_bars_per_index, max_b_value);
for i = 1:max_b_value
current_group_values = grouped_data{i};
if ~isempty(current_group_values)
plot_matrix(1:length(current_group_values), i) = current_group_values;
end
end
figure;
% Use the 'bar' function. By default, it creates grouped bars if the input is a matrix.
h = bar(plot_matrix);
xticks(1:max_b_value);
xticklabels(arrayfun(@num2str, 1:max_b_value, 'UniformOutput', false)); % Label ticks with numbers
xlabel('Index from B');
ylabel('Value from A');
title('Values from A Grouped by Index from B');
grid on;
0 Comments
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!