Лабы / ОКМвТС лабы / лаб5_Построение гистограммы последовательности данных при пом среды Matlab
Часто при проведении физического эксперимента или компьютерного моделирования приходится иметь дело с большим объемом данных. Поэтому актуальным является вопрос их наглядного представления. Численные данные можно оформить в виде графиков или диаграмм различных видов. Можно привести следующие примеры диаграмм и графиков: линейная диаграмма, столбиковая диаграмма, полосчатая диаграмма, кумулятивная кривая (данные накапливаются с течением времени), пиктограмма (данные представляются в виде стилизованных изображений), логарифмическая диаграмма, круговая диаграмма и т.д. Гистограмма (столбиковая диаграмма) – это последовательность столбцов, каждый из которых опирается на один раздельный интервал, а высота столбца – это частота или количество случаев. Принято распределять горизонтальную шкалу на один раздельный интервал вправо и влево от полученного диапазона. Середина столбца совмещается с серединой интервала, на практике ее обычно изображают в форме контура, опуская вертикальные линии. Наряду с понятием «гистограмма» используется понятие «полигон распределения». Полигон распределения – это та же гистограмма, но линии соединяют середины столбцов каждого разрядного интервала. Так как на разрядах справа и слева от разрядов распределения частот, частота имеет нулевое значение, поэтому полигон распределения продолжают до горизонтальной оси в середине интервала ниже меньшей оценки и выше высшей оценки. Гистограмма наиболее легка для восприятия и используется в тех случаях когда всего одно распределение. Если надо сравнить два или более распределений, используют полигон, чтобы избежать запутанной картины.
При построении гистограммы (т.е. графического изображения распределения некоторой величины) необходимо задавать определенное число бинов, определяя тем самым, сколько данных попадет в каждый бин и графически изображать это в виде столбиковой или ступенчатой диаграммы. Бин – это число разбиений переменной на интервалы, относительно которой и будет вычисляться и строиться распределение. Например, если студенты имеют рост от 150 см до 200 см, то можно разбить этот интервал ростов на 10 бинов, по 5 см в каждом, т.е это интервалы от 150см до 155см и т.д. Итак , гистограмма показывает сколько студентов попадает в каждый интервал ростов или бинов.
В Matlab существует функция hist, которая при обращении к ней в виде hist(y) вычисляет и рисует гистограмму с 10 бинами, равномерно распределенными между y max
и y min . Кроме того, функция hist(y) может иметь второй аргумент. Если этот аргумент –
целое число, то это число определяет число бинов. Если второй аргумент – вектор, то этот вектор определяет центры используемых бинов. В этом случае центры бинов должны быть равноотстоящими, а координаты этих центров должны быть расположены в возрастающем порядке. При нарушении любого из этих условий результат становится непредсказуемым.
Классическая гистограмма характеризует числа попаданий значений элементов вектора Y в М интервалов с представлением этих чисел в виде столбцовой диаграммы. Для получения данных для гистограммы функция hist (у) может быть записана следующим образом:
N=hist(Y) возвращает вектор чисел попаданий для 10 интервалов, выбираемых автоматически. Если Y – матрица, то выдается массив данных о числе попаданий для ее столбцов.
N=hist(Y,М) аналогична рассмотренной выше команде, но используется М интервалов (где М – скаляр).
N=hist(Y,Х). Данная команда возвращает числа попаданий элементов вектора Y в интервалы, центры которых заданы элементами вектора Х.
Пример. Построить гистограмму для 1000 случайных чисел и вывести вектор с данными о
Reading an image and getting information
To read images into the MATLAB environment you use the function imread, whose basic syntax is: imread(‘filename’).
Other informative functions are: numel(f), to calculate the total number of pixels in the image; size(f), which gives the row and column dimensions of an image, in our example 576px X 809px; whos(f), function which displays additional information about an array. In our example, uint8 is one of the image classes supported by Matlab, indicating that unsigned 8-bit integers in the range [0,255] (1 byte per element) are used to represent pixel values.
Finally we display our test image with: imshow(f) .
Image histograms
The histogram of a digital image with the possible levels of intensity in the range [0, G] is defined as a discrete function:
Where rk is the k-th intensity in the range [0, G] and nk is the number of pixels in the image where the intensity level is rk. The value of G is 255 for class uint8 (8 bits), and 65535 for images of class uint16 (16 bits). Note that G = L-1 for class uint8 and uint16.
Sometimes you need to work with normalized histograms, obtained simply by dividing all elements of h(rk) by the total number of pixels in the image, which we denote with n:
where k = 0, 1, 2, …, L-1. From probability theory, we recognize p(rk) is an estimate of the probability of occurrence of rk level intensity.
The main function of the toolbox to treat image histograms is imhist with the basic syntax:
where f is the input image, h is its histogram, and b is the number of clusters used in forming the histogram (if b is not included, b = 256 is used by default. A cluster (bin) is simply a subdivision of the intensity scale. For example, if we are working with images uint8 and b=2, then the intensity scale is divided into two ranges: from 0 to 127 and from 128 to 255. The resulting histogram will have two values: h(1), equal to the number of pixels in the image with values in the range [0, 127] and h(2), equal to the number of pixels with values in the range [128, 255].
We get the normalized histogram using the espression:
p = imhist(f, b)/numel(f)
the numel(f) function gives the number of elements in the array f (i.e. the number of pixels in the image).
Bar histograms
The easiest way to plot your histogram on the screen is to use imhist with no specified parameters: imhist(f). This is the histogram display default in the toolbox. However, there are many other ways to plot a histogram. Histograms can also be plotted using bar charts. To do this we can use the function:
bar(horz,z,w)
where z is a row vector containing the points for plotting, horz is a vector the same size of z that contains horizontal scale increases, and width is a number between 0 and 1. In other words, the values of horz give the horizontal increases and the values of z are the corresponding vertical values. If horz is omitted, the horizontal axis is divided in units from 0 to length(z). When width is 1, the bars touch each other; when is 0, the bars are just vertical lines. The default is 0.8.
When you print a bar graph, it is customary to reduce the resolution of the horizontal axis into bands. The following commands produce a bar chart with the horizontal axis divided into groups of about 10 levels:
The fourth statement in the preceding code was used to expand the lower range of the vertical axis and to set the horizontal axis. One of the axis function syntax forms is:
axis([horzmin horzmax vertmin vertmax])
which sets the minimum and maximum values in the horizontal and vertical axes.
You can add a title to the chart using the function title, whose basic syntax is title(‘titlestring’) where titlestring is a string of characters that will appear on the title, centered above the graph.
Stem plots
Another type of chart is stem, which is similar to a bar chart. The syntax is:
stem(horz,z,’LineSpec’,’fill’)
where z is the row vector that contains plotting points and horz is the same as the function bar. If omitted, the horizontal axis is divided into units from 0 to length (z), as above. The third parameter LineSpec is a triplet of values that respectively indicate the color, the type of line drawn and the marker type that will be used.
For example, stem(horz, h, r — o) produces a chart where lines and markers are red, lines are dashed and markers are little circles. If fill is used, the marker is filled with the color specified in the first element of the triplet.
In a next article, we will talk about histogram equalization, a simple way to increase the dynamic range of an image.
Histogram in MATLAB
In this tutorial, we will discuss how to plot a histogram of given data using the histogram() and histogram2() function in MATLAB.
Please enable JavaScript
Create Histogram of Vectors in MATLAB
To create a histogram of the given vector, you can use the histogram() function in MATLAB. For example, let’s create a histogram of a given vector. See the code below.
In the above code, we created the histogram of a random vector. In the output, the properties of the histogram, and we can change these properties. For example, let’s change the face color of the histogram using the FaceColor property, the edge color using the EdgeColor property and, the number of bins using the NumBins property. See the code below.
The face color of the histogram is changed to green, the edge color changed to red, and the number of bins is changed to 10. You can also change other histogram properties as you like.
Create Categorical Histogram in MATLAB
You can also create a categorical histogram using the histogram() function. You can define values in the categorical array like some names etc., and you have to give each categorical variable a value that will be shown as height in the histogram. For example, let’s create a histogram of three categorical variables: Yes , No , and Not Sure . See the code below.
In the above code, we created a categorical histogram of three variables. We have assigned each variable a different value. For example, we assigned the value 7 to the variable Yes , 8 to the variable No , and 9 to the variable Not Sure . The value 7 repeated seven times in the variable Vector means the variable Yes will be shown in a histogram with height 7 and so on. You can add as many categorical variables as you like in the histogram.
Create Normalized Histogram in MATLAB
We can normalize a histogram using the Normalization property inside the histogram() function. For example, let’s create a histogram from random numbers and then normalize it using the Normalization property. See the code below.
The above histogram is normalized using probability normalization. You can use other normalizations as well, like count normalization.
Plot Multiple Histograms on the Same Figure in MATLAB
We can also plot multiple histograms on the same figure using the hold function. For example, let’s plot two histograms on the same figure. See the code below.
In the above code, we plotted two histograms on the same figure. You can plot as many plots as you like on the same figure, and MATLAB will give them a separate color automatically. You can also give each histogram your desired color. You can also add legends to the histograms using the legend() function to separate them from one another.
Save a Histogram in MATLAB
You can save a histogram using the savefig() function in MATLAB, and you can load the saved histogram using the openfig() function. See the code below.
In the above code, Hist is the variable where the histogram is stored. Check this link for more information.
Bivariate Histogram in MATLAB
If you want to create a histogram of two variables, you can use the histogram2() function. For example, let’s plot a histogram of two vectors. See the code below.
In the above code, we plotted a bivariate histogram from two vectors. You can also add a color bar using the colorbar function, which will add colors to the histogram according to the height of the bins. The color of the bins will change from colder to hotter with an increase in the bin’s height and vise versa. For example, let’s add a color bar to the above bivariate histogram. See the code below.
You can also change the view of the histogram using the view() function. For example, let’s change the view of the above bivariate histogram from 3D to 2D. See the code below.
You can also change other properties of the bivariate histogram using the same function and properties as used in the above histograms. For example, you can change the face color using the FaceColor property, edge color using the EdgeColor property, number of bins using the NumBins property, and normalization using the Normalization property, etc. You can also save and load the bivariate histograms using the savefig() and openfig() functions. Check this link for more information.
Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.
Histogram in Matlab
By Priya Pedamkar

Introduction to Histogram in Matlab
Histogram is a representation of any statistical information showing the frequency of data items in successive intervals. MATLAB supports plotting histogram feature that enables the user to create a bar graph for any vector or matrix and grouping the data into bins using an automatic binning algorithm. For each bin, the area represents the frequency of occurrence of the data, not the height. It supports customization in histogram presentation.
Syntax:
Hadoop, Data Science, Statistics & others
In earlier versions, hist() and histc() were used to generate histogram plots. In later versions those functions are replaced with new functions with advanced capabilities i.e. histogram(), histcounts() and discretize().
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
The syntax for the above-recommended functions are as follows:
- histogram(X, a1,a2,…. an)
- histcounts(X, a1,a2,…. an)
- discretize(X, a1,a2,…. an)
Where X: Data input in the form of vector or matrix.
Creation of Histogram in Matlab: MATLAB makes it a single click action to create a histogram for any data. A histogram can be created by using the inbuilt function histogram().
Example:
The below code is written to generate 100 random numbers and histogram() is used to plot a histogram for the generated data.
Code:
data = randn(100,1);
h = histogram(data)
Output:

Once any histogram object is created, it can be altered by altering its property values, that makes changes in the properties of bins and thus in the display.
Properties of Histogram in Matlab
Various properties that are featured for the histogram in MATLAB, are as follows:
1. Bins
| Parameter | Description |
| NumBins | Decides the number of bins to be generated. |
| BinWidth | Decides the width of each bin. |
| BinEdges | A vector of which the first element of the vector determines the edge of the first bin and the last element decides the edges of the last bin of the histogram. |
| Binlimits | Sets the limits for the input vector/matrix values. |
| BinLimitModes | Decides mode of setting the limits. |
| BinMethod | Choose the algorithm to configure bin width. |
2. Categories
This property allows to plot histogram for each category defined in the input categorical array. If bin count is specified, categories sets the associated category descriptions in the plot.
This property contains parameters such as mentioned below:
| Parameter | Description |
| DisplayOrder | Decides the order of bars based on height. |
| NumDisplayBins | Decides the number of categories to be displayed. |
| ShowOthers | Decides about the visibility of the additional bar which contains excluded elements of selected categories. |
3. Data
This value gets distributed over a histogram plot among the bins. This property consists of different parameters such as:
| Parameter | Description |
| Values | Decides the number of data elements to be added to a specific bin. |
| Normalization | Applies a specific type of normalization on the data such as count, probability, countdensity, pdf, cumcount, etc. |
| BinCounts | Accepts the bin count as input from an external bin calculation method instead of histogram data binning. |
| BinCountsMode | Represents the mode of deciding bin counts. |
4. Color and Styling
| Parameter | Description |
| DisplayStyle | Decides the style to impose on the histogram display. |
| Orientation | Decides upon the orientation of the bars on the histogram plot- vertical or horizontal. |
| BarWidth | Regulates the separation of categorical bars. |
| FaceColor | Sets the color of the bars. |
| EdgeColor | Sets the color of the edges. |
| FaceAlpha | Decides on the transparency of the bars. |
| EdgeAlpha | Decides on the transparency of the edges. |
| LineStyle | Sets style of the bar outlines. |
| LineWidth | Sets the width of the bar outlines. |
5. Legend
This property in the MATLAB adds descriptive labels to the plots. It comprises of:
| Parameter | Description |
| DisplayName | Sets the text to be added to the description for the axes. |
| Annotation | Controls the inclusion of the objects in a legend and sets excluded objects as an annotation object. |
6. Interactivity
| Parameter | Description |
| Visible | Sets the visibility of an object. |
| DataTipTemplate | Decides on the content that appears on a data tip. |
| UIContextMenu | Sets the context menu for an object, displayed on right-click over the object. |
| Selected | Manages the selection mode of the object. |
| SelectionHighlight | Decides the visibility of selection handlers around an object. |
7. Callbacks
| Parameter | Description |
| ButtonDownFcn | Accepts a function as a value which is to be executed when an object is clicked. |
| CreateFcn | Accepts a function as a value which is to be executed when an object is created. |
| DeleteFcn | Accepts a function as a value which is to be executed when an object is deleted. |
8. Callback Execution Control
| Parameter | Description |
| Interruptible | Determines whether the callback function can be interrupted or not. |
| BusyAction | Determines how the interruption in callback function will be handled. |
| PickableParts | Sets the context menu for an object, displayed on right-click over the object. |
| Selected | Used to enable/disable capturing mouse clicks. |
| HitTest | Decides response on the captured mouse clicks on the Histogram plot. |
| BeingDeleted | Used to store the status of the execution of DeleteFcn callback. |
9. Parent/Child
| Parameter | Description |
| Parent | Axes, Polar axes, Transform objects or Group objects are specified as a parent. |
| Child | This property is a read-only element which is used to view a list of data tips that are plotted in the histogram. |
| HandleVisibility | Accepts a function as a value which is to be executed when an object is deleted. |
10. Identifiers
| Parameter | Description |
| Type | Represents the type of graphic object. |
| Tag | Serves as an object identifier. |
| UserData | Stores arbitrary data on an object. |
Examples of Histogram in Matlab
Let’s understand the usage of different attributes referring to various examples given below:
Example #1 – Changing Bin Counts
Code:
data = randn(100,1);
nbins = 10;
h = histogram(data,nbins)
Output:

Example #2 – Changing Bin Width
Code:
data = randn(100,1);
histogram(data,’BinWidth’,2)
Output:

Example #3 – Changing Normalization Type
Code:
data = randn(100,1);
h = histogram(data,’Normalization’,’countdensity’)
Output:

Example #4 – Changing Display Style
Code:
data = randn(100,1);
h = histogram(data,’DisplayStyle’,’stairs’)
Output:

Example #5 – Changing Color of the Bars
Code:
data = randn(100,1);
h = histogram(data,’FaceColor’,’#A2142F’)
Output:

A histogram plot lets you to understand and to analyze the set of continuous data under a frequency distribution. It is advantageous over a bar chart as it allows to divide data into classes in terms of bins which helps to do inspection over a specific category of data as required.
Additional Note:
- The function histogram() creates a histogram object having modifiable properties within.
- Histogram() and histcount() have common built-in options, automatic binning and normalization features.
- The primary calculation function for histogram i.e. histcounts() exhibits consistent behavior.
- Discretize() has extended feature about deciding placements of the bin for each element.
Recommended Articles
This is a guide to Histogram in Matlab. Here we discuss the Creation of Histogram in Matlab and its properties along with its examples and Code Implementation. You can also go through our suggested articles to learn more –