how to plot multiple bars in one figure in matlab

To plot multiple bars in one figure in MATLAB, you can use the bar function along with specifying the positions of the bars. Here is an example:

main.m
% Create some sample data
x = [1 2 3 4 5];
y1 = [10 12 15 13 9];
y2 = [8 10 12 11 7];

% Create a figure
figure;

% Plot the first bar graph
bar(x, y1);
hold on;  % Enable hold on to plot multiple bar graphs in one figure

% Plot the second bar graph
bar(x, y2);

% Customize the plot
title('Multiple Bar Graphs');
xlabel('x');
ylabel('y');
legend('y1', 'y2');

% Disable hold on to release the figure for new plots
hold off;
426 chars
24 lines

In this example, we have two sets of data y1 and y2 associated with the same x-values x. By calling the bar function twice, we can plot both sets of data as two separate bar graphs in the same figure. The hold on command enables us to plot multiple bar graphs on the same figure, while hold off disables it for subsequent plots.

Make sure to customize the figure as desired by adding a title, axis labels, and a legend to distinguish the bars.

related categories

gistlibby LogSnag