- Ensure Correct Dimensions: Make sure the x and y inputs to the text function are vectors of the same length.
- Iterate Over Subplots: If you are using a loop to create multiple subplots, ensure that each subplot has its own corresponding labels.
How to label each bar in a subplot?
2 views (last 30 days)
Show older comments
Hello all. Is there a way to label each bar in a bar plot when used in subplot. I tried with same code as used for normal bar chart, but wasn't able to find the solution. Your help is appreciated.
For normal bar chart
f=figure;
bar(xval2,per_cond1,0.4)
labels=[70.2,19.8,10];
text(xval2, per_cond1, cellstr(num2str(labels)), 'VerticalAlignment','bottom', ...
'HorizontalAlignment','center')
But the same when used for subplot, It shows error
subplot(2,2,i),bar(xval2,combined_graph_100m(:,2),0.4)
labels=[70.8,19.2,10];
text(xval2, combined_graph_100m, cellstr(num2str(labels)), 'VerticalAlignment','bottom', ...
'HorizontalAlignment','center')
But there is an error popping up which says
??? Error using ==> text
Value must be a column or row vector
0 Comments
Answers (1)
Prateekshya
on 14 Oct 2024
Hello Devela,
The error message you are encountering suggests that the inputs to the text function are not in the correct format. In particular, the x and y coordinates provided to text should be vectors of the same length, corresponding to the positions on the plot where you want to place the labels.
In your subplot example, you are likely passing an entire matrix ( combined_graph_100m ) to the text function instead of a specific column or row. Here is how you can fix the issue:
Here is an example of how you can modify your code to work with subplots:
% Example data
xval2 = 1:3; % x-values for the bars
combined_graph_100m = [70.8, 19.2, 10; 60, 25, 15]; % Example data for subplots
% Create a 2x2 subplot
figure;
for i = 1:2
subplot(2, 2, i);
y_values = combined_graph_100m(i, :); % Extract data for this subplot
bar(xval2, y_values, 0.4);
% Labels corresponding to the data
labels = y_values; % Use the same values for labels or define separately
% Add text labels to each bar
text(xval2, y_values, cellstr(num2str(labels')), 'VerticalAlignment', 'bottom', ...
'HorizontalAlignment', 'center');
title(['Subplot ' num2str(i)]);
end
You will be able to see a plot like:
I hope this helps!
0 Comments
See Also
Categories
Find more on Subplots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!