## Overview

This document contains exploratory plots for ordinal response data as well as the R code that generates these graphs. The plots presented here are based on simulated data ([see: PKPD Datasets](PKPD_Datasets.html)). Data specifications can be accessed on [Datasets](Datasets.html) and Rmarkdown template to generate this page can be found on [Rmarkdown-Template](Rmarkdown/Multiple_Ascending_Dose_PKPD_ordinal.Rmd). You may also download the Multiple Ascending Dose PK/PD dataset for your reference ([download dataset](Data/Multiple_Ascending_Dose_Dataset2.csv)).

Ordinal data can be thought of as categorical data that has a natural order. For example, mild, moderate or severe. Another example could be Grade 1, Grade 2, Grade 3. Ordinal data can also come out of stratifying continuous data, for example binning a continuous variable into quartiles, or defining (arbitrary or meaningful) cutoffs for a continuous variable. Since ordinal data has a natural order, it is important to preserve that order when creating plots. 

## Setup

```{r, echo = TRUE, warning=FALSE, message=FALSE}
# remove reference to home directory in libPaths
.libPaths(grep("home", .libPaths(), value=TRUE, invert=TRUE))

# add localLib to libPaths for locally installed packages
.libPaths(c("localLib", .libPaths()))

# will load from first filepath first, then look in .libPaths for more packages not in first path
# version matches package in first filepath, in the case of multiple instances of a package

# library(rmarkdown)
library(gridExtra)
library(grid)
library(ggplot2)
library(dplyr)
library(RxODE)
library(caTools)

#flag for labeling figures as draft
  draft.flag      = TRUE

## ggplot settings
theme_set(theme_bw(base_size=12))

```


## Define Useful Graphics Functions

```{r}

# annotation of plots with status of code
AnnotateStatus <- function(draft.flag, log.y=FALSE, log.x=FALSE, fontsize=7, color="grey") {
  
  x.pos <- -Inf
  if (log.x)
    x.pos <- 0
  
  y.pos <- -Inf
  if (log.y)
    y.pos <- 0
  
  if(draft.flag) {
    annotateStatus <- annotate("text",
                               label="DRAFT",
                               x=x.pos, y=y.pos,
                               hjust=-0.1, vjust=-1.0,
                               cex=fontsize,
                               col=color, alpha=0.7, fontface="bold")
  } else {
    annotateStatus <- NULL
  }
  
  return(annotateStatus)
}

```

## Load Dataset

```{r, warning=FALSE, message=FALSE}
my.data <- read.csv("../Data/Multiple_Ascending_Dose_Dataset2.csv")

# Define order for factors
my.data$TRTACT <- factor(my.data$TRTACT, levels = unique(my.data$TRTACT[order(my.data$DOSE)]))

my.data$Severity <- my.data$LIDV
my.data[my.data$CMT!=5,]$Severity <- NA
my.data$Severity_label <- factor(plyr::mapvalues(my.data$Severity,c(1,2,3), c("Mild", "Moderate","Severe")), levels = c("Mild","Moderate","Severe"))
```


## Provide an overview of the data

Summarize the data in a way that is easy to visualize the general trend of PD over time and between doses. Using summary statistics can be helpful, e.g. Mean +/- SE, or median, 5th & 95th percentiles. Consider either coloring by dose or faceting by dose. Depending on the amount of data one graph may be better than the other.

### PK and PD marker over time, colored by Dose, median, 5th, 95th percentiles by nominal time

Does the effect appear to increase and decrease quickly on a short time scale, or does is occur over a longer time scale? Do the PK and PD profiles appear to be on the same time scale, or does the PD seem delayed compared to the PK? Is there clear separation between the profiles for different doses? Does the effect appear to increase with increasing dose? Do you detect a saturation of the effect?

```{r, cache = TRUE, fig.width = 10, fig.height = 4, warning = FALSE, message= FALSE}
data_to_plot <- list()  
data_to_plot[[1]] <- my.data[my.data$CMT==2,]
data_to_plot[[1]]$TRTACT <- factor(data_to_plot[[1]]$TRTACT, levels = rev(levels(data_to_plot[[1]]$TRTACT)))

data_to_plot[[2]] <- my.data[my.data$CMT==5,]
data_to_plot[[2]]$TRTACT <- factor(data_to_plot[[2]]$TRTACT, levels = rev(levels(data_to_plot[[2]]$TRTACT)))
data_to_plot[[2]]$Response <- factor(data_to_plot[[2]]$Severity_label, levels = rev(levels(data_to_plot[[2]]$Severity_label)))

data_to_plot[[2]]$DAY <- floor(data_to_plot[[2]]$TIME/24 )

ggs <- list()
for(iplot in 1:length(data_to_plot)){
  
     if(iplot == 1){
  
  gg <- ggplot(data = data_to_plot[[iplot]], 
               aes(x=NOMTIME/24,y=LIDV, color = TRTACT, fill = TRTACT))+theme_bw()
  gg <- gg + stat_summary(geom="errorbar", 
                          fun.data=function(y){
                            data.frame(y=mean(y),
                                       ymin = mean(y)-qt(0.975,length(y))*sqrt(stats::var(y)/length(y)),
                                       ymax = mean(y)+qt(0.975,length(y))*sqrt(stats::var(y)/length(y))
                          )}, size = 1, width = 0)
  gg <- gg + stat_summary(geom="point", fun.y=mean)
  gg <- gg + stat_summary(aes(group = TRTACT), geom="line", 
                          fun.y=mean)+ scale_x_continuous(breaks = seq(-1,8,1))
      gg <- gg + scale_y_log10() + annotation_logticks(base = 10, sides = "l", color = rgb(0.5,0.5,0.5))
    gg <- gg + ylab("Concentration (ng/mL)")

    }else{
      gg <- ggplot(data = data_to_plot[[iplot]], aes(x = factor(DAY), fill = Response)) + theme_bw()
gg <- gg + geom_bar(position = "fill") + scale_y_continuous(labels = scales::percent)
gg <- gg + ylab("Responder Rate (%)") + guides(fill=guide_legend("")) #+ theme(legend.position = "bottom")
gg <- gg + facet_grid(TRTACT~.)
gg <- gg + scale_fill_brewer(palette=6)
    }
  gg <- gg + guides(color=guide_legend(""),fill=guide_legend(""))
  gg <- gg  + xlab("Time (days)")
  ggs[[iplot]] <- gg
}

grid.arrange(ggs[[1]], ggs[[2]], ncol = 2)
```

### PK and PD marker over time, faceted by Dose, mean +/- 95% CI by nominal time

```{r, cache = TRUE, fig.width = 10, fig.height = 6, warning = FALSE, message= FALSE}
data_to_plot <- list()  
data_to_plot[[1]] <- my.data[my.data$CMT==2,]
data_to_plot[[2]] <- my.data[my.data$CMT==5&my.data$DOSE>0,]
data_to_plot[[2]]$Response <- factor(data_to_plot[[2]]$Severity_label, levels = rev(levels(data_to_plot[[2]]$Severity_label)))
data_to_plot[[2]]$DAY <- floor(data_to_plot[[2]]$TIME/24 )

ggs <- list()
for(iplot in 1:length(data_to_plot)){
  if(iplot == 1){
    gg <- ggplot(data = data_to_plot[[iplot]], 
               aes(x=NOMTIME/24,y=LIDV))+theme_bw()
  gg <- gg + stat_summary(geom="errorbar", 
                          fun.data=function(y){
                            data.frame(y=mean(y),
                                       ymin = mean(y)-qt(0.975,length(y))*sqrt(stats::var(y)/length(y)),
                                       ymax = mean(y)+qt(0.975,length(y))*sqrt(stats::var(y)/length(y))
                          )}, size = 1)
  gg <- gg + stat_summary(geom="point", fun.y=mean, size = 2)
  gg <- gg + stat_summary(aes(group = TRTACT), geom="line", 
                          fun.y=mean)
  gg <- gg + guides(color=guide_legend(""),fill=guide_legend("")) + scale_x_continuous(breaks = seq(-1,8,1))
    gg <- gg + scale_y_log10() + annotation_logticks(base = 10, sides = "l", color = rgb(0.5,0.5,0.5))
    gg <- gg + ylab("Concentration (ng/mL)")
    }else{
      gg <- ggplot(data = data_to_plot[[iplot]], aes(x = factor(DAY), fill = Response)) + theme_bw()
gg <- gg + geom_bar(position = "fill") + scale_y_continuous(labels = scales::percent)
gg <- gg + ylab("Responder Rate (%)") + guides(fill=guide_legend("")) + theme(legend.position = "bottom")
gg <- gg + scale_fill_brewer(palette=6)

    }
  
  gg <- gg  + xlab("Time (days)")
  gg <- gg + facet_grid(~TRTACT)
  ggs[[iplot]] <- gg
}

grid.arrange(ggs[[1]], ggs[[2]], ncol = 1)
```

```{r, cache = TRUE, fig.width = 8, fig.height = 4, warning = FALSE, message= FALSE}
data_to_plot <- list() 
data_to_plot[[1]] <- my.data[my.data$CMT==2&my.data$DOSE!=0,
                             c("TIME","NOMTIME","LIDV","ID","DOSE","TRTACT","CENS","PROFDAY")]
data_to_plot[[1]]$Concentration <- data_to_plot[[1]]$LIDV
data_to_plot[[1]]$LIDV <- NULL

data_to_plot[[2]] <- my.data[my.data$CMT==5&my.data$DOSE!=0,
                             c("TIME","NOMTIME","LIDV","ID","DOSE","Severity_label","TRTACT","CENS","PROFDAY")]
data_to_plot[[2]]$LIDV <- NULL

data_to_plot2 <- merge(data_to_plot[[1]],data_to_plot[[2]],by=c("TIME","NOMTIME","ID","DOSE","TRTACT","CENS","PROFDAY"))

data_to_plot2$TRTACT <- factor(data_to_plot2$TRTACT, levels = rev(levels(data_to_plot2$TRTACT)))

gg <- ggplot(data = data_to_plot2, aes(y=Concentration,x=NOMTIME/24))+theme_bw()
gg <- gg + geom_jitter(data = data_to_plot2[data_to_plot2$CENS==0,], 
                       aes(color = Severity_label, shape = Severity_label),  width = 0.1, height = 0.0, alpha = 0.75)
gg <- gg + geom_jitter(data = data_to_plot2[data_to_plot2$CENS==1,], 
                       aes(color = Severity_label, shape = Severity_label), color = "red", shape=8,  width = 0.1, height = 0.0, alpha = 0.75)
gg <- gg + geom_boxplot(aes(group = factor(NOMTIME/24)),width = 0.5, fill = NA, outlier.shape=NA) 
gg <- gg + scale_y_log10() + annotation_logticks(base = 10, sides = "l", color = rgb(0.5,0.5,0.5))
gg <- gg + guides(color=guide_legend(""),fill=guide_legend(""), shape=guide_legend(""))
gg <- gg + xlab("Time (days)") + scale_x_continuous(breaks = seq(0,8))
gg <- gg + ylab("Trough Concentration (ng/mL)")
gg

```


## Explore variability


### PK and PD marker over time, colored by Dose, dots & lines grouped by individuals

```{r, cache = TRUE, fig.width = 10, fig.height = 6, warning = FALSE, message= FALSE}
data_to_plot <- list() 
data_to_plot[[1]] <- my.data[my.data$CMT==2,]
data_to_plot[[2]] <- my.data[my.data$CMT==5,]

set.seed(12345)
data_to_plot[[2]]$Severity2 <- jitter(data_to_plot[[2]]$Severity, amount=0.1)
data_to_plot[[2]]$time2 <- jitter(data_to_plot[[2]]$TIME, amount=0.1*24)

ggs <- list()
for(iplot in 1:length(data_to_plot)){
  data_to_plot[[iplot]]$TRTACT <- factor(data_to_plot[[iplot]]$TRTACT, levels = rev(levels(data_to_plot[[iplot]]$TRTACT)))
  if(iplot == 1){
    gg <- ggplot(data = data_to_plot[[iplot]], aes(x=TIME/24,y=LIDV,group=ID, color = TRTACT))+theme_bw()
    }else{
      gg <- ggplot(data = data_to_plot[[iplot]], aes(x=time2/24,y=Severity2,group=ID, color = TRTACT))+theme_bw()
    }
  gg <- gg + geom_line(alpha = 0.5)
  gg <- gg  + xlab("Time (days)") + scale_x_continuous(breaks = seq(-1,8,1))
  if(iplot == 1){
    gg <- gg + geom_point(data = data_to_plot[[iplot]][data_to_plot[[iplot]]$CENS==0,], shape=19, alpha = 0.2)
    gg <- gg + geom_point(data = data_to_plot[[iplot]][data_to_plot[[iplot]]$CENS==1,], shape=8, color = "red", alpha = 0.5)
    # gg <- gg + scale_shape_manual(values = c(1,8)) 
    gg <- gg + scale_y_log10() + annotation_logticks(base = 10, sides = "l", color = rgb(0.5,0.5,0.5))
    gg <- gg + ylab("Concentration (ng/mL)")
  }else{
    gg <- gg + geom_point(alpha = 0.2)
    gg <- gg + ylab("Severity")
  }
  gg <- gg + guides(color=guide_legend(""),fill=guide_legend(""),shape=FALSE) 
  ggs[[iplot]] <- gg
}

grid.arrange(ggs[[1]], ggs[[2]], ncol = 1)
```

### PK and PD marker over time, faceted by Dose, dots & lines grouped by individuals

```{r, cache = TRUE, fig.width = 10, fig.height = 6, warning = FALSE, message= FALSE}
data_to_plot <- list()  
data_to_plot[[1]] <- my.data[my.data$CMT==2,]
data_to_plot[[2]] <- my.data[my.data$CMT==5&my.data$DOSE>0,]

set.seed(12345)
data_to_plot[[2]]$Severity2 <- jitter(data_to_plot[[2]]$Severity, amount=0.1)
data_to_plot[[2]]$time2 <- jitter(data_to_plot[[2]]$TIME, amount=0.1*24)

ggs <- list()
for(iplot in 1:length(data_to_plot)){
  if(iplot == 1){
    gg <- ggplot(data = data_to_plot[[iplot]], aes(x=TIME/24,y=LIDV,group=ID))+theme_bw()
  }else{
    gg <- ggplot(data = data_to_plot[[iplot]], aes(x=time2/24,y=Severity2,group=ID))+theme_bw()
  }
  gg <- gg + geom_line(alpha = 0.2)
  gg <- gg + xlab("Time (days)") + scale_x_continuous(breaks = seq(-1,8,1))
  gg <- gg + facet_grid(~TRTACT)
  if(iplot == 1){
    gg <- gg + geom_point(aes(shape=factor(CENS), color = factor(CENS)), alpha = 0.2)
    gg <- gg + scale_shape_manual(values = c(19,8)) 
    gg <- gg + scale_color_manual(values = c(rgb(0,0,0), rgb(1,0,0)))
    gg <- gg + scale_y_log10() + annotation_logticks(base = 10, sides = "l", color = rgb(0.5,0.5,0.5))
    gg <- gg + ylab("Concentration (ng/mL)")
  }else{
    gg <- gg + geom_point(alpha = 0.2)
    gg <- gg + ylab("Severity")
  }
  gg <- gg + guides(color=FALSE,fill=FALSE,shape=FALSE) 
  ggs[[iplot]] <- gg
}

grid.arrange(ggs[[1]], ggs[[2]], ncol = 1)
```

## Explore Exposure-Response Relationship

```{r, cache = TRUE, fig.width = 8, fig.height = 2, warning = FALSE, message= FALSE}
data_to_plot <- list() 
data_to_plot[[1]] <- my.data[my.data$CMT==2&my.data$DOSE!=0&my.data$PROFDAY==5,
                             c("TIME","LIDV","ID","DOSE","TRTACT","CENS")]
data_to_plot[[1]]$Concentration <- data_to_plot[[1]]$LIDV
data_to_plot[[1]]$LIDV <- NULL

data_to_plot[[2]] <- my.data[my.data$CMT==5&my.data$DOSE!=0&my.data$PROFDAY==5,
                             c("TIME","LIDV","ID","DOSE","Severity_label","TRTACT","CENS")]
data_to_plot[[2]]$LIDV <- NULL

data_to_plot2 <- merge(data_to_plot[[1]],data_to_plot[[2]],
                       by=c("TIME","ID","DOSE","TRTACT","CENS"))

data_to_plot2$TRTACT <- factor(data_to_plot2$TRTACT, 
                               levels = rev(levels(data_to_plot2$TRTACT)))

gg <- ggplot(data = data_to_plot2, aes(y=Concentration,x=Severity_label))+theme_bw()
gg <- gg + geom_jitter(data = data_to_plot2[data_to_plot2$CENS==0,], 
                       aes(color = TRTACT), shape=19,  width = 0.1, height = 0.0, alpha = 0.5)
gg <- gg + geom_jitter(data = data_to_plot2[data_to_plot2$CENS==1,], 
                       color = "red", shape=8,  width = 0.1, height = 0.0, alpha = 0.5)
gg <- gg + geom_boxplot(width = 0.5, fill = NA, outlier.shape=NA) 
gg <- gg + scale_y_log10() 
gg <- gg + guides(color=guide_legend(""),fill=guide_legend(""))
gg <- gg + coord_flip() 
gg <- gg + xlab("Severity") + ylab("Concentration (ng/mL)")
gg

```


### Explore covariate effects on Exposure-Response Relationship

Stratify exposure-response plots by covariates of interest to explore whether any key covariates impact response independent of exposure. For examples of plots and code startifying by covariate, see [Continuous PKPD Covariate Section](Multiple_Ascending_Dose_PKPD_continuous.html#explore_covariate_effects_on_exposure-response_relationship)

### Individual response vs exposure hysteresis plots

Using geom_path you can create hysteresis plots of response vs exposure. Including details like arrows or colors can be helpful to indicate the direction of time.

If most of the arrows point up and to the right or down and to the left, this indicates a positive relationship between exposure and response (i.e. increasing exposure -> increasing response). Arrows pointing down and to the right or up and to the left indicate a negative relationship.

In a hysteresis plot, you want to determine whether the path is curving, and if so in what direction. If you detect a curve in the hysteresis plot, this indicates there is a delay between the exposure and the response. Normally, a clockwise turn indicates that increasing exposure is associated with (a delayed) increasing response, while a counter clockwise turn indicates increasing concentration gives (a delayed) decreasing response.

In the plots below, most of the hysteresis paths follow a counter clockwise turn, with most arrows pointing up and to the right or down and to the left, indicating the effect increases in a delayed manner with increasing concentration.

```{r, cache = TRUE, fig.width = 8, fig.height = 15, warning = FALSE, message= FALSE}
data_to_plot <- list() 
data_to_plot[[1]] <- my.data[my.data$CMT==2&my.data$DOSE!=0,c("TIME","LIDV","ID","DOSE","TRTACT")]
data_to_plot[[1]]$Concentration <- data_to_plot[[1]]$LIDV
data_to_plot[[1]]$LIDV <- NULL

data_to_plot[[2]] <- my.data[my.data$CMT==5&my.data$DOSE!=0,c("TIME","LIDV","ID","DOSE","Severity_label","TRTACT")]
data_to_plot[[2]]$Response <- factor(data_to_plot[[2]]$Severity_label, levels = rev(levels(data_to_plot[[2]]$Severity_label)))
data_to_plot[[2]]$LIDV <- NULL

data_to_plot2 <- merge(data_to_plot[[1]],data_to_plot[[2]],by=c("TIME","ID","DOSE","TRTACT"))
data_to_plot2<- data_to_plot2[order(data_to_plot2$TIME),]

gg <- ggplot(data = data_to_plot2, aes(x=Concentration,y=Response,group = ID, color = TIME))+theme_bw()
gg <- gg + geom_path(arrow=arrow(length=unit(0.15,"cm")))
gg <- gg + ylab("Severity") + xlab("Concentration (ng/mL)")
gg <- gg + scale_x_log10() + annotation_logticks(base = 10, sides = "b", color = rgb(0.5,0.5,0.5)) #+ scale_y_log10()
gg+facet_wrap(~ID+TRTACT, ncol = 5)

```

## R Session Info
```{r}
sessionInfo()
```