Histograms in detail
A histogram is a graphical representation of statistical data that groups data points into specified ranges. The rectangular bars in a histogram represent frequencies, with their heights proportional to the frequency of values in each range. Unlike bar graphs, histograms do not have gaps between bars.
Creating Histograms in R
Histograms in R can be created using the hist() function.
Syntax:
hist(v, main, xlab, xlim, ylim, breaks, col, border)
Parameters:
v: Numeric values used to create the histogram.main: Title of the chart.col: Color of the bars.xlab: Label for the horizontal axis.border: Color of the bar borders.xlim: Range of values on the x-axis.ylim: Range of values on the y-axis.breaks: Defines the width of each bar.
Example 1: Creating a Simple Histogram
# Creating data for the graph
values <- c(10, 25, 15, 8, 20, 18, 30, 12, 22, 28, 35)
# Creating the histogram
hist(values, xlab = "Frequency of Items",
col = "blue", border = "black")
Output:

Example 2: Setting X and Y Ranges
# Creating data for the graph
values <- c(10, 25, 15, 8, 20, 18, 30, 12, 22, 28, 35)
# Creating the histogram
hist(values, xlab = "Frequency of Items", col = "blue",
border = "black", xlim = c(0, 40),
ylim = c(0, 5), breaks = 5)
Output:

Example 3: Adding Labels Using text()
# Creating data for the graph
values <- c(10, 25, 15, 8, 20, 18, 30, 12, 22, 28, 35, 110, 50, 80, 95)
# Creating the histogram
hist_data <- hist(values, xlab = "Weight", ylab = "Frequency",
col = "purple", border = "black",
breaks = 5)
# Adding labels
text(hist_data$mids, hist_data$counts, labels = hist_data$counts,
adj = c(0.5, -0.5))
Output:

Example 4: Histogram with Non-Uniform Width
# Creating data for the graph
values <- c(10, 25, 15, 8, 20, 18, 30, 12, 22, 28, 35, 110, 50, 80, 95)
# Creating the histogram
hist(values, xlab = "Weight", ylab = "Frequency",
xlim = c(10, 120),
col = "purple", border = "black",
breaks = c(5, 55, 60, 70, 75, 80, 100, 140))
Output:

Leave a Reply