R hist() Function - Plotting Histograms

R 语言实例R Language Examples

The R hist() function is used to plot histograms and display the distribution of data.

A histogram divides data into several intervals (bins) and displays the frequency or relative frequency of data within each interval.

The syntax of the hist() function is as follows:

hist(x, breaks = "Sturges", freq = NULL, col = NULL,
     main = paste("Histogram of", xname))

Parameter description:

  • xA numeric vector.

  • breaksInterval division method: can be a number (number of bins), a vector (breakpoint positions), or an algorithm name.

  • freqWhether to display frequency (TRUE) or density (FALSE).

Examples

# Generate test score data
set.seed(123)
scores <- rnorm(200, mean = 70, sd = 10)

# Plot histogram
hist(scores,
     main = "Test Score Distribution",
     xlab = "Score",
     ylab = "Frequency",
     col = "skyblue",
     border = "white",
     breaks = 15)

# Add mean and median lines
abline(v = mean(scores), col = "red", lwd = 2, lty = 2)
abline(v = median(scores), col = "blue", lwd = 2, lty = 3)
legend("topright",
       legend = c("Mean", "Median"),
       col = c("red", "blue"), lty = c(2, 3), lwd = 2)

Executing the above code will display a histogram, including a red mean line and a blue median line.

R 语言实例R Language Examples

Other Extensions