Bar and histogram plots help us see data clearly by showing counts or values as bars. They make it easy to compare groups or understand data distribution.
0
0
Bar and histogram plots in MATLAB
Introduction
To compare sales numbers for different products in a store.
To show how many students scored in different grade ranges.
To visualize the frequency of different ages in a group.
To display monthly expenses by category.
To understand the spread of test scores in a class.
Syntax
MATLAB
bar(X, Y) histogram(data) % X and Y are vectors for bar plot % data is a vector for histogram
bar(X, Y) creates a bar plot where X is categories and Y is values.
histogram(data) creates a histogram showing data distribution.
Examples
Simple bar plot with categories 1 to 4 and their values.
MATLAB
x = [1 2 3 4]; y = [10 20 15 5]; bar(x, y);
Histogram of 100 random numbers from a normal distribution.
MATLAB
data = randn(100,1); histogram(data);
Bar plot with named categories on x-axis.
MATLAB
categories = {'A', 'B', 'C'};
values = [5 7 3];
bar(values);
set(gca, 'XTickLabel', categories);Sample Program
This code first shows a bar plot of fruit sales with category names. Then it creates a histogram of 100 random integers from 1 to 10.
MATLAB
% Create sample data
categories = {'Apples', 'Bananas', 'Cherries'};
sales = [30 45 25];
% Bar plot of sales
bar(sales);
set(gca, 'XTickLabel', categories);
title('Fruit Sales');
ylabel('Number Sold');
% Create random data for histogram
data = randi([1 10], 100, 1);
% New figure for histogram
figure;
histogram(data);
title('Random Data Distribution');
xlabel('Value');
ylabel('Frequency');OutputSuccess
Important Notes
Use set(gca, 'XTickLabel', categories) to label bars with names.
Histograms automatically group data into bins to show frequency.
Use figure; to create a new plot window if you want multiple plots.
Summary
Bar plots show values for categories as bars.
Histograms show how data is spread across ranges.
Both help visualize data clearly and quickly.