The “geom_histogram” Function in R
Package: ggplot2
Purpose: To create histograms in ggplot.
General Class: Geometric object for displaying the distribution of a continuous variable.
Required Argument(s): None
Notable Optional Arguments:
mapping: Aesthetic mappings.
data: The data to be displayed in this layer.
stat: The statistical transformation to use on the data for this layer.
position: Position adjustment.
binwidth: Width of the bins.
binaxis: The direction of the bins, “x” or “y”.
center: The center of the first bin.
boundary: A boundary between two bins.
closed: Should the rightmost bin be closed in “right” mode?
pad: If FALSE, overrides the default aesthetics to allow the bars to extend beyond the data.
show.legend: Should this layer be included in the legends?
Example:
# Example usage
library(ggplot2)
# Create a data frame
my_data <- data.frame(
values = rnorm(100)
)
# Create a ggplot object with a histogram using geom_histogram
my_plot <- ggplot(data = my_data, aes(x = values)) +
geom_histogram(binwidth = 0.5, fill = "lightblue", color = "blue") +
labs(title = "Histogram Example", x = "Values", y = "Frequency")
# Print the plot
print(my_plot)In this example, the geom_histogram function from the ggplot2 package is used to create a histogram. The function allows customization of aesthetics such as fill color, line color, and transparency. The binwidth argument controls the width of the bins in the histogram.