---
title: "Graphics in qwraps2"
author: "Peter DeWitt"
output:
 rmarkdown::html_vignette:
   toc: true
   number_sections: true
vignette: >
 %\VignetteIndexEntry{qwraps2-graphics}
 %\VignetteEngine{knitr::rmarkdown}
 %\VignetteEncoding{UTF-8}
---


```{r label = "setup", include = FALSE}
knitr::opts_chunk$set(collapse = TRUE)
```


There are several graphics generated within qwraps2.  The naming convention
for the "quick" plots was inspired by the ggplot2 function qplot.  The
development, flexibility, and robustness of these functions vary.  Some "tips
and tricks" are provided.

```{r }
library(qwraps2)
packageVersion("qwraps2")
library(ggplot2)
```



# qacf: Autocorrelation Plots

Generate an example data set.

```{r }
set.seed(42)
n <- 250
x1 <- x2 <- x3 <- x4 <- vector('numeric', length = n)
x1[1] <- runif(1)
x2[1] <- runif(1)
x3[1] <- runif(1)
x4[1] <- runif(1)

# white noise
Z.1 <- rnorm(n, 0, 1)
Z.2 <- rnorm(n, 0, 2)
Z.3 <- rnorm(n, 0, 5)

for(i in 2:n)
{
  x1[i] <- x1[i-1] + Z.1[i] - Z.1[i-1] + x4[i-1] - x2[i-1]
  x2[i] <- x2[i-1] - 2 * Z.2[i] + Z.2[i-1] - x4[i-1]
  x3[i] <- x3[i-1] + x2[i-1] + 0.2 * Z.3[i] + Z.3[i-1]
  x4[i] <- x4[i-1] + runif(1, 0.5, 1.5) * x4[i-1]
}
testdf <- data.frame(x1, x2, x3, x4)

# Base acf plot for one variable
acf(testdf$x1)

# qacf plot for one variable
qacf(testdf$x1)
qacf(testdf$x1, show_sig = TRUE)

```
```{r fig.width = 5, fig.height = 5}
# more than one variable
acf(testdf)
qacf(testdf)
qacf(testdf, show_sig = TRUE)
```


## Tips and tricks

The implementation of qacf is based on the use of
`r  backtick(stats::acf)  `
to produce the statistics needed for the plot.  If you want to get at the
data itself to build your own acf plot you can extract the data frame from
the qacf return:

```{r }
acf_plot_data <- qacf(testdf)$data
head(acf_plot_data)
```


# qblandaltman: Bland Altman Plot

Introduced in [@altman1983measurement] and [@bland1986statistical], the
qblandaltman method builds ggplot2 style Bland Altman plots.  For examples we
use the provided pefr data set which was transcribed from
[@bland1986statistical].  See
`r  backtick(vignette("qwraps2-data-sets", package = "qwraps2"))  `
For more details on that data set.

The following replicates the figures in [@bland1986statistical].

Using the first measurement only:

```{r }
pefr_m1 <-
  cbind("Large" = pefr[pefr$measurement == 1 & pefr$meter == "Wright peak flow meter", "pefr"],
        "Mini"  = pefr[pefr$measurement == 1 & pefr$meter == "Mini Wright peak flow meter", "pefr"])
```


A standard x-y style plot and a correlation coefficient suggests that the two
meters provide reasonably similar results.

```{r }
cor(pefr_m1)

qplot(x = pefr_m1[, 1],
      y = pefr_m1[, 2],
      geom = "point",
      xlab = "Large Meter",
      ylab = "Mini Meter",
      xlim = c(0, 800),
      ylim = c(0, 800)) +
geom_abline(slope = 1)
```


However, for many reasons, this the above is misleading.  One simple note:
correlation is not a metric for agreement, i.e., perfect agreement would be
shown if all the data points fell on the line of equality were as perfect
correlation occurs when the data points are co-linear.

The Bland Altman plot plots the average value on the x-axis and the
difference in the measurements on the y-axis:

```{r }
qblandaltman(pefr_m1) +
xlim(0, 800) +
ylim(-100, 100) +
xlab("Average of two meters") +
ylab("Difference in the measurements")
```


There is no distinct relationship between the differences and the average,
but the difference in the measurements between the two meters was observed to
range between
`r  paste(range(apply(pefr_m1, 1, diff)), collapse = " and ")  `
liters per minute.  Such a discrepancy between the meters is not observable
from the simple x-y plot.

Reliability, or repeatability, of measurements can also be investigated with
a Bland Altman plot.

```{r }
pefr_mini <-
  cbind(m1 = pefr[pefr$measurement == 1 & pefr$meter == "Mini Wright peak flow meter", "pefr"],
        m2 = pefr[pefr$measurement == 2 & pefr$meter == "Mini Wright peak flow meter", "pefr"])

qblandaltman(pefr_mini)
```



# qkmplot: Kaplan Meier Plots

```{r }
# create a survfit object
require(survival)
leukemia.surv <- survival::survfit(survival::Surv(time, status) ~ x, data = survival::aml)

# base R km plot
survival:::plot.survfit(leukemia.surv, conf.int = TRUE, lty = 2:3, col = 1:2)

```
```{r fig.width = 5}
# qkmplot
qkmplot(leukemia.surv, conf_int = TRUE)

# build a data.frame for plotting km curves, this could be helpful for
# creating bespoke plots
leukemia_km_data <- qkmplot_bulid_data_frame(leukemia.surv)
head(leukemia_km_data, 3)

```
```{r fig.width = 5}
qkmplot(leukemia_km_data)

```
```{r fig.width = 5}
# intercept only plot
intonly_fit <- survival::survfit(survival::Surv(time, status) ~ 1, data = survival::aml)
survival:::plot.survfit(intonly_fit, conf.int = TRUE)
qkmplot(intonly_fit, conf_int = TRUE)
```


# qroc: Receiver Operating Curve

```{r }
data(diamonds, package = "ggplot2")

# Create two logistic regression models
fit1 <- glm(I(price > 2800) ~ cut * color, data = diamonds, family = binomial())
fit2 <- glm(I(price > 2800) ~ cut + color + clarity, data = diamonds, family = binomial())

# Easiest way to get an ROC plot:
qroc(fit1)
qroc(fit2)

# Create two data sets, this will also let you get the AUC out
data1 <- qroc_build_data_frame(fit1)
data2 <- qroc_build_data_frame(fit2)

auc(data1)
auc(data2)

# Plotting the ROC from the data set can be done too
qroc(data1)

# Add the AUC value to the plot title
qroc(data2) + ggtitle(paste("Fit 2\nAUC =", round(auc(data2), 2)))

# build a data set for plotting to ROCs on one plot
plot_data <- rbind(cbind(Model = "fit1", data1),
                   cbind(Model = "fit2", data2))
qroc(plot_data) + aes(color = Model)

# with AUC in the legend
plot_data <- rbind(cbind(Model = paste("Fit1\nauc =", round(auc(data1), 3)), data1),
                   cbind(Model = paste("Fit2\nauc =", round(auc(data2), 3)), data2))
qroc(plot_data) +
  theme_bw() +
  aes(color = Model, linetype = Model) +
  theme(legend.position   = "bottom",
        legend.text.align = 0.5)
```



# Session Info

```{r label = "sessioninfo"}
sessionInfo()
```

