qqcomp() and ppcomp() in Highcart R

352 views Asked by At

I am trying to make some plots using Highchart package in R. My plots are a qqcomp() and ppcomp(), I'd like to replicate this using highchart. I am able to do this using ggplot2 but I think they would look much better in Highchart.

This is my code:

library(fitdistrplus)
library(highcharter)
library(ggplot2)
x <- c(164.26,  229.61, 25.07,17.82,111.71,15.33,9849.52,35.8,354.69,255.12,166.36,1371.07,362.58,4212.29,8424.57)

fit.lnorm <- fitdist(x,"lnorm",method="mle", start = NULL)
fit.gamma <- fitdist(x,"gamma", method = "mle", lower = c(0, 0))

qcomp <- qqcomp(list(fit.lnorm, fit.gamma), 
                xlegend = "bottomright",
                xlab = "Cuantiles teóricos",
                ylab = "Cuantiles empíricos",
                fitlty = 1,
                fitcol = c("red1","springgreen2"),
                plotstyle = "ggplot",
                addlegend = FALSE)

pcomp <- ppcomp(list(fit.lnorm, fit.gamma),
                xlegend = "bottomright",
                xlab = "Probabilidades teóricas",
                ylab = "Probabilidades empíricas",
                fitlty = 1,
                fitcol = c("red1","springgreen2"),
                plotstyle = "ggplot",
                addlegend = FALSE)

qcomp <- qcomp + theme_minimal() + ggtitle("Q-Q Plot")
pcomp <- pcomp + theme_minimal() + ggtitle("P-P Plot")
1

There are 1 answers

2
Iaroslav Domin On

You can extract pretty much all the information needed to recreate the plot from the ggplot object. In particular:

Data

qcomp$data
#>          values   ind      sdata
#> 1  6.496176e+00 lnorm   15.32480
#> 2  1.992613e+01 lnorm   17.83156
#> 3  3.769184e+01 lnorm   25.06524
#> 4  6.127904e+01 lnorm   35.78934
#> 5  9.260956e+01 lnorm  111.69299
...

Mapping

qcomp$mapping
#> Aesthetic mapping: 
#> * `group`  -> `ind`
#> * `colour` -> `ind`
#> * `shape`  -> `ind`
#> * `size`   -> `ind`
#> * `x`      -> `values`
#> * `y`      -> `sdata`

With the above we can construct a highchart plot like this:

# data to draw the diagonal line
max_val <- max(qcomp$data[,c("values", "sdata")])
diag_data <- data.frame(x = c(0, max_val), y = c(0, max_val))


highchart() %>% 
  hc_plotOptions(
    scatter = list(marker = list(symbol = "circle")),
    line = list(marker = list(enabled = FALSE), enableMouseTracking = FALSE)
  ) %>% 
  hc_add_series(diag_data, "line", color ="gray", hcaes(x, y),
                showInLegend = FALSE) %>% 
  hc_add_series(qcomp$data, "scatter", hcaes(values, sdata, group = ind)) %>% 
  hc_xAxis(title = list(text = qcomp$labels$x)) %>% 
  hc_yAxis(title = list(text = qcomp$labels$y)) %>% 
  hc_title(text = qcomp$labels$title) %>% 
  hc_add_theme(hc_theme_elementary())

enter image description here