Drawing uniform Distributions with ggplot in R

708 views Asked by At

I want to draw different uniform distributions in R, preferably with ggplot. When attempting to draw the pdf of U(0.35,0.55), it looks like there are values around the edges (i.e. the parameter values, in this case 0.35 and 0.55) that have a probability that is different from what it should be. The output can be seen here: uniform distribution example

This is consistent across different parameters as inputs of the uniform distribution, and does not seem to be a scale issue.

A code example that reproduces similar results:

#parameters
alpha_1 <- 0.35
beta_1 <- 0.55
alpha_2 <- 0.5
beta_2 <- 0.7
alpha_3 <- 0.1
beta_3 <- 0.3

base <- ggplot() + xlim(-1, 2)


base + 
        geom_function(aes(colour = "state 1"), fun = dunif, args = list(alpha_1, beta_1)) +
        geom_function(aes(colour = "state 2"), fun = dunif, args = list(alpha_2, beta_2)) +
        geom_function(aes(colour = "state 3"), fun = dunif, args = list(alpha_3, beta_3))

Using stat_function instead of geom_function does not change anything.

However, the following works:

curve(dunif(x, min = alpha_1, max = beta_1), 
            from = 0, to = 1, 
            n = 100000, 
            col = "blue", 
            lwd = 2, 
            add = F, 
            yaxt = "n",
            ylab = 'probability')
curve(dunif(x, min = alpha_2, max = beta_2), 
     from = 0, to = 1, 
     n = 100000, 
     col = "red", 
     lwd = 2, 
     add = T, 
     yaxt = "n",
     ylab = 'probability')
curve(dunif(x, min = alpha_3, max = beta_3), 
     from = 0, to = 1, 
     n = 100000, 
     col = "black", 
     lwd = 2, 
     add = T, 
     yaxt = "n",
     ylab = 'probability')

How can I get this to work in ggplot? It seems to me the issue might be this:

n values along the x-axis are evaluated to get coordinates for the graph. Around the parameters (a,b) these are, e.g. at a+0.0001 and a-0.0001. The straight line between these coordinates would not be perfectly vertical. I am not sure whether that is the correct diagnosis, but in any case I would appreciate any help. Thanks!

1

There are 1 answers

0
Konstantin B On BEST ANSWER

This is easily solved by increasing the number of evaluation points, as Gregor Thomas has helpfully pointed out in a comment. The following adjusted code works just as intended:

library(ggplot2)
#parameters
alpha_1 <- 0.35
beta_1 <- 0.55
alpha_2 <- 0.5
beta_2 <- 0.7
alpha_3 <- 0.1
beta_3 <- 0.3

base <- ggplot() + xlim(-1, 2)


base + 
        stat_function(aes(colour = "state 1"), fun = dunif, args = list(alpha_1, beta_1), n = 10001) +
        stat_function(aes(colour = "state 2"), fun = dunif, args = list(alpha_2, beta_2), n = 10001) +
        stat_function(aes(colour = "state 3"), fun = dunif, args = list(alpha_3, beta_3), n = 10001)

Where the key change is to add n=10001 to every stat_function call.