Histograms and density plots help us see how data is spread out. They show where most values are and how they group together.
0
0
Histogram and density plots in R Programming
Introduction
To understand the distribution of exam scores in a class.
To check if data follows a normal pattern before analysis.
To compare the spread of heights between two groups.
To find out if there are any unusual values in sales data.
Syntax
R Programming
hist(x, breaks = "Sturges", col = "blue", main = "Histogram", xlab = "Values") density_data <- density(x) plot(density_data, main = "Density Plot", xlab = "Values")
hist() creates a histogram from numeric data.
density() calculates data density, and plot() draws the density curve.
Examples
Basic histogram with default settings.
R Programming
hist(data_vector)
Histogram with 20 bins, green color, and custom title and x-axis label.
R Programming
hist(data_vector, breaks = 20, col = "green", main = "My Histogram", xlab = "Data")
Calculate and plot the density curve of the data.
R Programming
density_data <- density(data_vector) plot(density_data)
One-line code to plot density with a red line and title.
R Programming
plot(density(data_vector), main = "Density Plot", col = "red")
Sample Program
This program creates 100 random numbers around 50 with some spread. It then shows a histogram and a density plot to visualize the data distribution.
R Programming
set.seed(123) data_vector <- rnorm(100, mean = 50, sd = 10) hist(data_vector, breaks = 15, col = "skyblue", main = "Histogram of Data", xlab = "Values") density_data <- density(data_vector) plot(density_data, main = "Density Plot of Data", xlab = "Values", col = "darkgreen")
OutputSuccess
Important Notes
Histograms group data into bins to show frequency.
Density plots smooth out the data to show distribution shape.
You can adjust the number of bins in histograms to see more or less detail.
Summary
Histograms and density plots help visualize how data values spread.
Use hist() for bar-style frequency plots and density() with plot() for smooth curves.
Adjusting parameters like bins and colors makes plots clearer and prettier.