Plotting Uniform Distributions In R With ggplot2

Hello there. This page is about plotting uniform distributions in R with the ggplot2 package. The approach I use is through making a function where the user specifies the minimum and maximum of the uniform distribution and then the function outputs the associated uniform distribution plot.

 


Creating The Uniform Distribution Plotting Function

This time around, I have decided to put ggplot2 code inside a function as the uniform distribution varies depending on the values of a and b (minimum and maximum values). The function is designed to adapt to different a and b values.

If the ggplot2 package is not installed into R/RStudio, type in the following to install ggplot2.

In R, load in the ggplot2 package by typing in

Recall that functions in R have the form of:

In the code below, I have the arguments as a and b for the uniform distribution and the xvals line sets the range for the x-values. The ggplot2 lines of codes takes in xvals as the xlimits for the plot, and the uniform distribution plots and labels adjusts to the a and b values.

The two stat_function() addons are for creating the probability density line and for the colour fill under the line. I have used 1/(b – a) as the upper limit for the y-limit as 1/(b – a) is the “height” of the uniform distribution.

In labs(), I have the paste0() function for title to adjust depending on the values of a and b. Having paste0() be adjustable allows for adjustable titles.

The two red geom_vlines are included to highlight the boundaries of the uniform distributions at a and b.

 


Examples

Once this function is set up in R, you can make function calls with your choice of values for a and b.

 

Leave a Reply