Search code examples
rggplot2probability-density

Error Creating a GEV distribution in ggplot


I was trying to create GEV distributions with ggplot but received a persistent error. I was, however, successful creating these curves using the "plot" function, just like this:

library(evir)

Gpdf <- plot(dgev(seq(1,500),mu=170.19, sigma=53.59, xi=0.09),type = 'l',col='black', lty = 
1, ylim = c(0,0.010), lwd = 5, ylab = "Density",xlab = "mm/day", cex.lab = 2, cex.axis = 2, 
main = "Global", cex.main = 4) + lines(dgev(seq(1,500),mu = 195.38, sigma = 63.13, xi = 
-0.05),type='l', col = 'blue', lty = 1, lwd = 5) 

enter image description here

ggplot attempt:

library(ggplot2)
library(evir)

Gpdf <- ggplot(geom_density(dgev(seq(1,500),mu = 170.19, sigma = 53.59, xi = 0.09), color = 
"black", size = 3, linetype = "solid", ylim = c(0,0.010), ylab = "Density", xlab= "mm/day", 
main = "Global", cex.main=4) + geom_density(dgev(seq(1,500),mu = 195.38, sigma = 63.13, xi = 
-0.05), col="blue", linetype = "solid") + theme(plot.title = element_text(size = 54))+ 
theme(axis.title = element_text(size = 54)) + theme(axis.text = element_text(size = 
54))+theme(panel.background = element_blank()) + theme(plot.title = element_text(size = 54, 
face = "bold")))

Which yields this error:

Error in dgev(seq(1, 500), mu = 170.19, sigma = 53.59, xi = 0.09) : 
unused arguments (mu = 170.19, sigma = 53.59, xi = 0.09)

Any help or feedback with this would be greatly appreciated!

Thanks!


Solution

  • If you use stat_function directly you won't need data, just define the arguments to dgev and pass them on to function you want to plot.

    library(evir)
    library(ggplot2)
    #> 
    #> Attaching package: 'ggplot2'
    #> The following object is masked from 'package:evir':
    #> 
    #>     qplot
    
    args1 <- list(mu = 170.19, sigma = 53.59, xi = 0.09)
    args2 <- list(mu = 195.38, sigma = 63.13, xi = -0.05)
    
    ggplot() +
      stat_function(fun = dgev, args = args1, color = "black", linewidth = 1.5) +
      stat_function(fun = dgev, args = args2, color = "blue", linewidth = 1.5) +
      xlim(1, 500) +
      labs(x = "mm/day", y = "Density") +
      theme_bw()
    

    Created on 2024-02-05 with reprex v2.0.2