########
#remotes::install_github("csdaw/ggprism")
#if "Error: Does not appear to be an R package (no DESCRIPTION)", 
#run Sys.setenv("TAR" = "internal")
library(ggprism)
########################
library(ggplot2)
library(tibble)
library(rlang)
library(patchwork)
####################
p1 <- ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  stat_summary(aes(fill = factor(dose)), na.rm = TRUE,
               geom = "col", fun = mean, colour = "black", size = 0.9) + 
  scale_y_continuous(limits = c(0, 30), expand = c(0, 0))

p2 <- p1 + theme_prism(base_size = 14)

p1 + p2

p3 <- p1 + theme_prism(palette = "mustard_field", base_size = 14)
p4 <- p1 + theme_prism(palette = "flames", base_size = 14)

p3 + p4

p <- ggplot(ToothGrowth, aes(x = factor(supp), y = len)) + 
  geom_boxplot(aes(colour = factor(supp), fill = factor(supp))) + 
  theme_prism(base_size = 14)

p1 <- p + scale_colour_prism(palette = "floral") + 
  scale_fill_prism(palette = "floral")

p2 <- p + scale_colour_prism(palette = "flames") + 
  scale_fill_prism(palette = "flames")

p1 + p2

#######################
p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_jitter(aes(shape = factor(dose)), width = 0.2, size = 2) + 
  scale_shape_prism() + 
  theme_prism() + 
  theme(legend.position = "none")

p1 <- p + scale_y_continuous(limits = c(0, 40), guide = "prism_minor")

p2 <- p + scale_x_discrete(guide = "prism_bracket") + 
  scale_y_continuous(limits = c(0, 40))

p3 <- p + scale_y_continuous(limits = c(0, 40), guide = "prism_offset")

p4 <- p + scale_y_continuous(limits = c(0, 40), guide = "prism_offset_minor")

(p1 + p2) / (p3 + p4)

df_p_val <- data.frame(
  group1 = "OJ",
  group2 = "VC",
  p.adj = 0.0606,
  y.position = 36
)

# make a plot
p1 <- ggplot(ToothGrowth, aes(x = factor(supp), y = len)) + 
  geom_boxplot(aes(fill = factor(supp))) + 
  scale_fill_prism(palette = "candy_bright") + 
  theme_prism() + 
  theme(legend.position = "none")

# add the p-value
p2 <- p1 + add_pvalue(df_p_val)

p1 

p2

tg <- ToothGrowth
tg$dose <- as.factor(tg$dose)

base <- ggplot(tg, aes(x = dose, y = len)) + 
  geom_violin(aes(colour = dose, fill = dose), trim = FALSE) + 
  geom_boxplot(aes(fill = dose), width = 0.2, colour = "black") + 
  scale_y_continuous(limits = c(-5, 40))

p_vals <- tibble::tribble(
  ~group1, ~group2, ~p.adj,   ~y.position,
  "0.5",   "1",     8.80e-14, 35,
  "0.5",   "2",     1.27e-7,  39
)
base

base + 
  scale_color_prism("floral") + 
  scale_fill_prism("floral") + 
  guides(y = "prism_offset_minor") + 
  theme_prism(base_size = 16) + 
  theme(legend.position = "none") + 
  add_pvalue(p_vals, label = "p = {p.adj}", tip.length = 0, label.size = 4)

library(ggnewscale)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
# construct the data.frame, log10 transform the agonist concentration
# convert the data.frame to long format, then remove any rows with NA
df <- data.frame(
  agonist = c(1e-10, 1e-8, 3e-8, 1e-7, 3e-7, 1e-6, 3e-6, 1e-5, 3e-5, 1e-4, 3e-4),
  ctr1 = c(0, 11, 125, 190, 258, 322, 354, 348, NA, 412, NA),
  ctr2 = c(3, 33, 141, 218, 289, 353, 359, 298, NA, 378, NA),
  ctr3 = c(2, 25, 160, 196, 345, 328, 369, 372, NA, 399, NA),
  trt1 = c(3, NA, 11, 52, 80, 171, 289, 272, 359, 352, 389),
  trt2 = c(5, NA, 25, 55, 77, 195, 230, 333, 306, 320, 338), 
  trt3 = c(4, NA, 28, 61, 44, 246, 243, 310, 297, 365, NA)
) %>% 
  mutate(log.agonist = log10(agonist)) %>% 
  pivot_longer(
    c(-agonist, -log.agonist), 
    names_pattern = "(.{3})([0-9])", 
    names_to = c("treatment", "rep"),
    values_to = "response"
  ) %>% 
  filter(!is.na(response))

head(df)
## # A tibble: 6 x 5
##        agonist log.agonist treatment rep   response
##          <dbl>       <dbl> <chr>     <chr>    <dbl>
## 1 0.0000000001         -10 ctr       1            0
## 2 0.0000000001         -10 ctr       2            3
## 3 0.0000000001         -10 ctr       3            2
## 4 0.0000000001         -10 trt       1            3
## 5 0.0000000001         -10 trt       2            5
## 6 0.0000000001         -10 trt       3            4
# plot the log10(agonist concentration) vs the response
p <- ggplot(df, aes(x = log.agonist, y = response))
# define model (note x and ec50 are swapped around because ec50 is already -ve)
dose_resp <- y ~ min + ((max - min) / (1 + exp(hill_coefficient * (ec50 - x))))
# fit separate curves to the data from the two treatment types
p <- p + geom_smooth(
  aes(colour = treatment),
  method = "nls", formula = dose_resp, se = FALSE,
  method.args = list(start = list(min = 1.67, max = 397, ec50 = -7, hill_coefficient = 1))
)
p

# apply a manual colour scale to the curves
p <- p + scale_colour_manual(
  labels = c("No inhibitor", "Inhibitor"),
  values = c("#00167B", "#9FA3FE")
)
p

# reset the colour scale, add the data points, then use a new colour scale
p <- p + ggnewscale::new_scale_colour() +
  geom_point(aes(colour = treatment, shape = treatment), size = 3) + 
  scale_colour_prism(
    palette = "winter_bright", 
    labels = c("No inhibitor",
               "Inhibitor")
  ) + 
  scale_shape_prism(
    labels = c("No inhibitor",
               "Inhibitor")
  )
p

# use the Winter Bright theme and make the size of all plot elements larger
p <- p + theme_prism(palette = "winter_bright", base_size = 16)
p

# adjust the axis limits, major tick positions, and axis guide
p <- p + scale_y_continuous(
  limits = c(-100, 500), 
  breaks = seq(-100, 500, 100),
  guide = "prism_offset"
)
p

# adjust the axis limits, major and minor tick positions, axis guide, and 
# axis text (aka. label) appearance
p <- p + scale_x_continuous(
  limits = c(-10, -3), 
  breaks = -10:-3,
  guide = "prism_offset_minor",
  minor_breaks = log10(rep(1:9, 7)*(10^rep(-10:-4, each = 9))),
  labels = function(lab) {
    do.call(
      expression,
      lapply(paste(lab), function(x) bquote(bold("10"^.(x))))
    )
  }
)
p

# remove the y axis title and legend title, change the x axis title and
# move the legend to the top left
p <- p + theme(
  axis.title.y = element_blank(),
  legend.title = element_blank(),
  legend.position = c(0.05, 0.95),
  legend.justification = c(0.05, 0.95)
) + 
  labs(x = "[Agonist], M")
p

dose_resp <- y ~ min + ((max - min) / (1 + exp(hill_coefficient * (ec50 - x))))

ggplot(df, aes(x = log.agonist, y = response)) + 
  geom_smooth(
    aes(colour = treatment),
    method = "nls", formula = dose_resp, se = FALSE,
    method.args = list(start = list(min = 1.67, max = 397, ec50 = -7, hill_coefficient = 1))
  ) + 
  scale_colour_manual(labels = c("No inhibitor", "Inhibitor"),
                      values = c("#00167B", "#9FA3FE")) + 
  ggnewscale::new_scale_colour() +
  geom_point(aes(colour = treatment, shape = treatment), size = 3) + 
  scale_colour_prism(palette = "winter_bright", 
                     labels = c("No inhibitor", "Inhibitor")) + 
  scale_shape_prism(labels = c("No inhibitor", "Inhibitor")) + 
  theme_prism(palette = "winter_bright", base_size = 16) + 
  scale_y_continuous(limits = c(-100, 500), 
                     breaks = seq(-100, 500, 100),
                     guide = "prism_offset") + 
  scale_x_continuous(
    limits = c(-10, -3), 
    breaks = -10:-3,
    guide = "prism_offset_minor",
    minor_breaks = log10(rep(1:9, 7)*(10^rep(-10:-4, each = 9))),
    labels = function(lab) {
      do.call(
        expression,
        lapply(paste(lab), function(x) bquote(bold("10"^.(x))))
      )
    }
  ) + 
  theme(axis.title.y = element_blank(),
        legend.title = element_blank(),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) + 
  labs(x = "[Agonist], M")

#install.packages("ggbeeswarm")
library(ggbeeswarm)
library(tidyverse)
## -- Attaching packages ------------------------------------------------------------------- tidyverse 1.3.0 --
## √ readr   1.4.0     √ stringr 1.4.0
## √ purrr   0.3.4     √ forcats 0.5.0
## -- Conflicts ---------------------------------------------------------------------- tidyverse_conflicts() --
## x purrr::%@%()         masks rlang::%@%()
## x purrr::as_function() masks rlang::as_function()
## x dplyr::filter()      masks stats::filter()
## x purrr::flatten()     masks rlang::flatten()
## x purrr::flatten_chr() masks rlang::flatten_chr()
## x purrr::flatten_dbl() masks rlang::flatten_dbl()
## x purrr::flatten_int() masks rlang::flatten_int()
## x purrr::flatten_lgl() masks rlang::flatten_lgl()
## x purrr::flatten_raw() masks rlang::flatten_raw()
## x purrr::invoke()      masks rlang::invoke()
## x dplyr::lag()         masks stats::lag()
## x purrr::list_along()  masks rlang::list_along()
## x purrr::modify()      masks rlang::modify()
## x purrr::prepend()     masks rlang::prepend()
## x purrr::splice()      masks rlang::splice()
library(rstatix)
## 
## Attaching package: 'rstatix'
## The following object is masked from 'package:stats':
## 
##     filter
wings_pvals <- wings %>%
  group_by(sex, measure) %>%
  rstatix::t_test(
    percent.change ~ genotype, 
    p.adjust.method = "BH", 
    var.equal = TRUE, 
    ref.group = "Tps1MIC/+"
  ) %>%
  rstatix::add_x_position(x = "measure", dodge = 0.9) %>% # dodge must match points
  mutate(label = c("***", "*", "P = 0.26", "***", "***", "P = 0.65"))

ggplot(wings, aes(x = measure, y = percent.change)) + 
  ggbeeswarm::geom_beeswarm(aes(fill = genotype), dodge.width = 0.9, shape = 21) + 
  facet_wrap(~ sex, scales = "free",
             labeller = labeller(sex = c(male = "\u2642", female = "\u2640"))) + 
  geom_hline(yintercept = 0, linetype = 2, size = 0.3) + 
  stat_summary(geom = "crossbar", aes(fill = genotype),fun = mean,
               position = position_dodge(0.9), colour = "red", size = 0.4, width = 0.7,
               show.legend = FALSE) + 
  add_pvalue(wings_pvals, y = 10, xmin = "xmin", xmax = "xmax", 
             tip.length = 0, fontface = "italic", 
             lineend = "round", bracket.size = 0.5) + 
  theme_prism(base_fontface = "plain", base_line_size = 0.7, 
              base_family = "sans") + 
  scale_x_discrete(guide = guide_prism_bracket(width = 0.15), 
                   labels = scales::wrap_format(5)) + 
  scale_y_continuous(limits = c(-20, 12), expand = c(0, 0),
                     breaks = seq(-20, 10, 5), guide = "prism_offset") + 
  labs(y = "% change") + 
  scale_fill_manual(values = c("#026FEE", "#87FFFF"), 
                    labels = c(expression("Tps"*1^italic("MIC")~"/ +"), 
                               expression("Tps"*1^italic("MIC")))) + 
  theme(legend.position = "bottom",
        axis.title.x = element_blank(),
        strip.text = element_text(size = 14),
        legend.spacing.x = unit(0, "pt"),
        legend.text = element_text(margin = margin(r = 20))) + 
  geom_text(data = data.frame(sex = factor("female", levels = c("male", "female")), 
                              measure = "Cell Number", 
                              percent.change = -18.5, 
                              lab = "(n = 10)"), 
            aes(label = lab)) + 
  guides(fill = guide_legend(override.aes = list(size = 3)))

#########################
#ref 
#https://mp.weixin.qq.com/s/lZWih1JHTwTaNSIO4S2WSg
#https://csdaw.github.io/ggprism/articles/ex2-wings.html
#https://csdaw.github.io/ggprism/