How to Plot Multiple Histograms in R?
In this article, we will discuss how to plot multiple histograms in the R Programming language.
Method 1: Multiple Histogram in Base R
To create multiple histograms in base R, we first make a single histogram then add another layer of the histogram on top of it. But in doing so some plots may clip off as axis are made according to the first plot. So, we can add the xlim, and the ylim parameters in the first plot to change the axis limit according to our dataset.
hist( data, col, xlim, ylim ) hist( data, col )
- data: determines the data vector to be plotted.
- xlim: determines the vector with x-axis limit.
- ylim: determines the vector with y-axis limit.
- col: determines the color of bars of the histogram.
Here, is basic multiple histograms made in the base R Language with help of hist() function.
Method 2: Multiple Histogram Using ggplot2
To create multiple histograms in ggplot2, we use ggplot() function and geom_histogram() function of the ggplot2 package. To visualize multiple groups separately we use the fill property of aesthetics function to color the plot by a categorical variable.
ggplot( df, aes( x, fill ) ) + geom_histogram( color, alpha )
- df: determines the data frame to be plotted.
- x: determines the data variable.
- fill: determines the color of bars in the histogram.
- color: determines the color of the boundary of bars in the histogram.
- alpha: determines the transparency of the plot.
Here, is basic multiple histograms made by using the geom_histogram() function of the ggplot2 package in the R Language.