plot a istogram in r

To plot a histogram in R, we can use the ggplot2 library. Here's a step-by-step guide using the built-in mtcars dataset:

main.r
# Load ggplot2 library
library(ggplot2)

# Load mtcars dataset
data(mtcars)

# Plot histogram of miles per gallon (mpg) variable
ggplot(mtcars, aes(x = mpg)) + geom_histogram(color = 'black', fill = 'white', binwidth = 2)
222 chars
9 lines

This code will create a histogram with the mpg variable as the x-axis, the count of occurrences as the y-axis, and a binwidth of 2. The bins are created automatically based on the data range.

We can customize the plot by adding labels, changing the binwidth, adjusting the color and fill, and more. The ggplot2 library offers a lot of flexibility in creating and customizing data visualizations.

gistlibby LogSnag