Multiplots

library(PKPDmisc) # for binning and other functions
library(ggplot2) #plotting
library(purrr) # dataset to handle lists
suppressMessages(suppressWarnings(library(dplyr)))
dat <- sd_oral_richpk %>% filter(ID <= 20)

Messy plot can't see individuals well

ggplot(dat, aes(x = Time, y = Conc, group= ID)) + 
  geom_line() +
  facet_wrap(~ID, scales= "free")

What we'd like to be able to do is split up into 'bins' of specified numbers of individuals to then plot out multiple plots

# this will automatically create a column of bins such that the
# specified number of individuals is in each bin, in this case
# 9 ids per bin

# split the original dataset into subdatasets corresponding to each bin (list of dataframes)
split_dat <- dat %>% 
  mutate(PLOTS = ids_per_plot(ID, 4)) %>% # default is 9 per subplot
  split(.[["PLOTS"]])

To handle plotting each subdataframe, you need to wrap your normal ggplot into a function. You will then apply this function with map to each subdataframe. So in this case it is just like a normal plot, but wrapped up in a function, which takes 1 argument (the dataframe) and outputs the plot

p_conc_time <- function(df) {
ggplot(df, aes(x = Time, y = Conc, group= ID)) + 
  geom_line() +
  facet_wrap(~ID, scales= "free")
}

To apply the above function we use map from purrr

split_dat %>% map(p_conc_time) 

As you can notice from the vignette, there is still a code-based output separating each subplot, which is not ideal for reporting. As such, there is a special function print_plots in PKPDmisc that will clean up the output slightly. It also automatically restarts the page numbering if knitting to PDF to page 1, making it each to extract only the pages related to plots to embed cleanly in other reports.

To use print_plots we want to save the ggplot output (rather than let it be printed directly) and give that to print plots.

plot_list <- split_dat %>% map(p_conc_time) 
print_plots(plot_list)
devtools::session_info()


Try the PKPDmisc package in your browser

Any scripts or data that you put into this service are public.

PKPDmisc documentation built on Dec. 18, 2017, 1:05 a.m.