rm(list=ls(all=TRUE))
#install.packages(metalite)
# install.packages(metalite.table1)
# install.packages(ggplot2)
# install.packages(haven)
# install.packages(plotly)
# install.packages(tidyr)
# install.packages("ggtext")

library(ggtext)
## Warning: package 'ggtext' was built under R version 4.2.3
library(metalite)
## Warning: package 'metalite' was built under R version 4.2.3
library(metalite.table1)
## Warning: package 'metalite.table1' was built under R version 4.2.3
library(haven)
## Warning: package 'haven' was built under R version 4.2.3
library(tidyr)
## Warning: package 'tidyr' was built under R version 4.2.3
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.3
library(DT)
## Warning: package 'DT' was built under R version 4.2.3
library(crosstalk)
## Warning: package 'crosstalk' was built under R version 4.2.3
path<-"//dc1/Project Workspace/UX003/Clinical/Clinical Operations/UX003-CL401/11.0 Biostatistics/AR2022_NOV/Stats/Publication data/datasets/"

PedSQL Dataset DRAFT - FOR EXPLORATORY PURPOSES ONLY

Pedsqcat <- read_sas(paste0(path, "Pedsqcat.sas7bdat"))
cat("## Dataset: PedSQL dataset \n mean1=Treated with Initial Baseline, \n mean2=Treated without Initial Baseline  mean3=Untreated")
## ## Dataset: PedSQL dataset 
##  mean1=Treated with Initial Baseline, 
##  mean2=Treated without Initial Baseline  mean3=Untreated

PedSQL Graphs

library(gridExtra)
## Warning: package 'gridExtra' was built under R version 4.2.3
Pedcasgr <- read_sas(paste0(path, "Pedcasgr.sas7bdat"))

Pedcasgr$freq1<-c(6,7,8,9)
Pedcasgr$mean1<-c(50,66.5,78,86)
Pedcasgr$mean2<-c(90,30,56,60)
# Define the colors for treatment regimens
treatment_colors <- c("Treated with Initial Baseline" = "green",
                      "Treated without Initial Baseline" = "blue",
                      "Untreated" = "orange")

ggplot(Pedcasgr, aes(x = avisitn)) +
  geom_line(aes(y = mean1, color = "Treated with Initial Baseline"), size = 1) +
  geom_line(aes(y = mean2, color = "Treated without Initial Baseline"), size = 1) +
  geom_line(aes(y = mean3, color = "Untreated"), size = 1) +
  geom_text(aes(x = avisitn, y = -1, label = freq1),  color = "green") +
  geom_text(aes(x = avisitn, y = -10, label = freq2),  color = "blue") +
  geom_text(aes(x = avisitn, y = -15, label = freq3),  color = "orange") +
  geom_hline(yintercept = 60.9, linetype = "dashed", color = "red", size = 1) +  # Make the line thicker
  annotate("text", x = -4, y = 50, label = "Average Score", vjust = -0.5, size = 6, color = "grey") +  # Place label above the line
  labs(title = "PedSQL Cognitive Fatigue Score by Treatment Regimen",
       x = "Visit (months)",
       y = "Cognitive Fatigue Score") +
  scale_y_continuous(limits = c(0, 100)) +
  scale_x_continuous(breaks = c(-8, 0, 6, 12, 24, 36, 48),
                     labels = c("Initial Baseline", "Month 0", "Month 6", "Year 1", "Year 2", "Year 3", "Year 4")) +
  scale_color_manual(name = "Treatment Regimen", values = treatment_colors) +
  theme_minimal()+
  theme(axis.line = element_line(color = "black"),  # Black x and y axis lines
        panel.grid.minor = element_blank(),# Remove minor grids
        panel.grid.major =element_blank(),   # Remove major grids
         plot.margin = margin(b = 100, unit = "pt"))  # Increase bottom margin
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## i Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 4 rows containing missing values (`geom_text()`).
## Removed 4 rows containing missing values (`geom_text()`).
## Removed 4 rows containing missing values (`geom_text()`).

library(ggplot2)
library(gridExtra)
library(ggpubr)
## Warning: package 'ggpubr' was built under R version 4.2.3
library(patchwork)
## Warning: package 'patchwork' was built under R version 4.2.3
library(gtable)
## Warning: package 'gtable' was built under R version 4.2.3
# Assuming Pedcasgr is your data frame and treatment_colors is previously defined

# Create the ggplot
p1 <- ggplot(Pedcasgr, aes(x = avisitn)) +
  geom_line(aes(y = mean1, color = "Treated with Initial Baseline"), size = 1) +
  geom_line(aes(y = mean2, color = "Treated without Initial Baseline"), size = 1) +
  geom_line(aes(y = mean3, color = "Untreated"), size = 1) +
  geom_hline(yintercept = 60.9, linetype = "dashed", color = "red", size = 1) +  # Make the line thicker
  annotate("text", x = -4, y = 50, label = "Average Score", vjust = -0.5, size = 6, color = "grey") +  # Place label above the line
  labs(title = "PedSQL Cognitive Fatigue Score by Treatment Regimen",
       x = "Visit (months)",
       y = "Cognitive Fatigue Score") +
  scale_y_continuous(limits = c(0, 100)) +
  scale_x_continuous(breaks = c(-8, 0, 6, 12, 24, 36, 48),
                     labels = c("Initial Baseline", "Month 0", "Month 6", "Year 1", "Year 2", "Year 3", "Year 4")) +
  scale_color_manual(name = "Treatment Regimen", values = treatment_colors) +
  theme_minimal()+
  theme(axis.line = element_line(color = "black"),  # Black x and y axis lines
        panel.grid.minor = element_blank(),# Remove minor grids
        panel.grid.major =element_blank())  


# Extract legend for the main plot
library(ggpubr)
legend <- get_legend(p1)
p1 <- p1 + theme(legend.position = "none")

# Transpose the frequency data and create a data frame suitable for the table
freq_data <- data.frame(t(data.frame(freq3 = Pedcasgr$freq3,  freq2 = Pedcasgr$freq2,freq1 = Pedcasgr$freq1 )))

freq_data$X1[which(is.na(freq_data$X1)==1)]=""

colnames(freq_data) <- c("Initial Baseline", "Month 0", "Month 6", "Year 1")

# Adjust hjust for each column individually
hjust_values <- c(0, 0.5, 0.5, 0.5)  # Set hjust for the first column to 0 (left-align)

tt3 <- ttheme_minimal(
  core=list(bg_params = list(fill = "white", col = "grey", lwd = 0.2),
            fg_params=list(col=c("orange", "blue" , "green"),
                           x=c(0.8,0.8,0.8),fontsize=12 ),#x is to adjust the position of value
            line = list(col = "black", lwd = 0.5))
) 



# Create a tableGrob without row names
 p2 <- gridExtra::tableGrob(freq_data, rows = NULL, cols = NULL, theme=tt3)
#p2 <- gridExtra::tableGrob(freq_data, rows = NULL, cols = NULL)


# grid.arrange(tableGrob(freq_data,theme=tt3),nrow=1)
# Set widths/heights to 'fill whatever space I have'
p2$widths <- unit(rep(1, ncol(p2)), "null")
p2$heights <- unit(rep(1, nrow(p2)), "null")


# Format table as plot
p3 <- ggplot() +
  annotation_custom(p2)


p1+legend+p3+ plot_layout(ncol = 2, widths = c(4, 2), heights=c(4,1))

library(ggplot2)
library(gridExtra)
library(ggpubr)
library(patchwork)
library(gtable)
# Assuming Pedcasgr is your data frame and treatment_colors is previously defined

# Create the ggplot
p1 <- ggplot(Pedcasgr, aes(x = avisitn)) +
  geom_line(aes(y = mean1, color = "Treated with Initial Baseline"), size = 1) +
  geom_line(aes(y = mean2, color = "Treated without Initial Baseline"), size = 1) +
  geom_line(aes(y = mean3, color = "Untreated"), size = 1) +
  geom_hline(yintercept = 60.9, linetype = "dashed", color = "red", size = 1) +  # Make the line thicker
  annotate("text", x = -4, y = 50, label = "Average Score", vjust = -0.5, size = 6, color = "grey") +  # Place label above the line
  labs(title = "PedSQL Cognitive Fatigue Score by Treatment Regimen",
       x = "Visit (months)",
       y = "Cognitive Fatigue Score") +
  scale_y_continuous(limits = c(0, 100)) +
  scale_x_continuous(breaks = c(-8, 0, 6, 12, 24, 36, 48),
                     labels = c("Initial Baseline", "Month 0", "Month 6", "Year 1", "Year 2", "Year 3", "Year 4")) +
  scale_color_manual(name = "Treatment Regimen", values = treatment_colors) +
  theme_minimal()+
  theme(axis.line = element_line(color = "black"),  # Black x and y axis lines
        panel.grid.minor = element_blank(),# Remove minor grids
        panel.grid.major =element_blank())  


# Extract legend for the main plot
library(ggpubr)
legend <- get_legend(p1)
p1 <- p1 + theme(legend.position = "none")

# Transpose the frequency data and create a data frame suitable for the table
freq_data <- data.frame(t(data.frame(freq3 = Pedcasgr$freq3,  freq2 = Pedcasgr$freq2,freq1 = Pedcasgr$freq1 )))

freq_data$X1[which(is.na(freq_data$X1)==1)]=""

colnames(freq_data) <- c("Initial Baseline", "Month 0", "Month 6", "Year 1")


# Define your theme
tt3 <- ttheme_minimal(
  core = list(
    bg_params = list(fill = "white", col = "grey", lwd = 0.2),
    fg_params = list(col = c("orange", "blue", "green"), x = c(0.8, 0.8, 0.8), fontsize = 12),
    line = list(col = "black", lwd = 0.5)
  )
)

# Create a tableGrob with the specified theme
p2 <- gridExtra::tableGrob(freq_data, rows = NULL, cols = NULL, theme = tt3)



# grid.arrange(tableGrob(freq_data,theme=tt3),nrow=1)
# Set widths/heights to 'fill whatever space I have'
p2$widths <- unit(rep(1, ncol(p2)), "null")
p2$heights <- unit(rep(1, nrow(p2)), "null")

# Find the index of the grob for the first cell in the first row
# Note: This might require adjustment depending on your table's structure
# first_cell_index <- min(which(p2$layout$name == "core-fg"))

# Adjust the x position of the first cell in the first row
# p2$grobs[[first_cell_index]]$x <- unit(0.1, "npc")
# p2$grobs[[3]]$x <- unit(0.1, "npc")

# Adjust the x position of the entire first column
# Assuming the table has headers, adjustment starts from the second grob
#first column
for (i in seq(1, 3, by = 1)) {
  p2$grobs[[i]]$x <- unit(0.1, "npc")
}
#second column
for (i in seq(4, 6, by = 1)) {
  p2$grobs[[i]]$x <- unit(0.6, "npc")
}
#third column
for (i in seq(7, 9, by = 1)) {
  p2$grobs[[i]]$x <- unit(0.7, "npc")
}

#forth column
for (i in seq(10, 12, by = 1)) {
  p2$grobs[[i]]$x <- unit(0.8, "npc")
}

# Format table as plot
p3 <- ggplot() +
  annotation_custom(p2)

p3

p1+legend+p3+ plot_layout(ncol = 2, widths = c(4, 2), heights=c(4,1))

library(ggplot2)
library(gridExtra)
library(ggpubr)
library(patchwork)
library(gtable)
# Assuming Pedcasgr is your data frame and treatment_colors is previously defined

Pedcasgr$Class="Class1"


# Create the ggplot
p1 <- ggplot(Pedcasgr, aes(x = avisitn)) +
  geom_line(aes(y = mean1, color = "Treated with Initial Baseline"), size = 1) +
  geom_line(aes(y = mean2, color = "Treated without Initial Baseline"), size = 1) +
  geom_line(aes(y = mean3, color = "Untreated"), size = 1) +
  geom_hline(yintercept = 60.9, linetype = "dashed", color = "red", size = 1) +  # Make the line thicker
  annotate("text", x = -4, y = 50, label = "Average Score", vjust = -0.5, size = 6, color = "grey") +  # Place label above the line
  labs(title = "PedSQL Cognitive Fatigue Score by Treatment Regimen",
       x = "Visit (months)",
       y = "Cognitive Fatigue Score") +
  scale_y_continuous(limits = c(0, 100)) +
  scale_x_continuous(breaks = c(-8, 0, 6, 12, 24, 36, 48),
                     labels = c("Initial Baseline", "Month 0", "Month 6", "Year 1", "Year 2", "Year 3", "Year 4")) +
  scale_color_manual(name = "Treatment Regimen", values = treatment_colors) +
  theme_minimal()+
  theme(axis.line = element_line(color = "black"),  # Black x and y axis lines
        panel.grid.minor = element_blank(),# Remove minor grids
        panel.grid.major =element_blank(),
        plot.margin = unit(c(1,1,1,1), "lines")) 


# Extract legend for the main plot
library(ggpubr)
legend <- get_legend(p1)
p1 <- p1 + theme(legend.position = "none")

# Transpose the frequency data and create a data frame suitable for the table
freq_data <- data.frame(t(data.frame(freq3 = Pedcasgr$freq3,  freq2 = Pedcasgr$freq2,freq1 = Pedcasgr$freq1 )))

freq_data$X1[which(is.na(freq_data$X1)==1)]=""

colnames(freq_data) <- c("Initial Baseline", "Month 0", "Month 6", "Year 1")

p2<-Pedcasgr%>%
  mutate(First=freq3,
         Second=freq2,
         Third=freq1)%>%pivot_longer(c(First, Second, Third), names_to = "layer", values_to = "label") %>% 
  ggplot(aes(x = avisitn)) +
  geom_text(aes(y = factor(layer, c("Third", "Second", "First")), label = label)) +
  labs(y = "", x = NULL) +
  theme_minimal() +
  theme(axis.line = element_blank(), axis.ticks = element_blank(), axis.text.x = element_blank(),
        panel.grid = element_blank(), strip.text = element_blank()) +
  facet_grid(~avisitn)

p2
## Warning: Removed 1 rows containing missing values (`geom_text()`).

p1+legend+p2+ plot_layout(ncol = 2, widths = c(5, 3), heights=c(4,1))
## Warning: Removed 1 rows containing missing values (`geom_text()`).

https://stackoverflow.com/questions/66200466/create-a-plot-with-a-table-under-the-plot

https://github.com/baptiste/gridextra/wiki/tableGrob#text-justification

https://patchwork.data-imaginist.com/articles/guides/layout.html

https://stackoverflow.com/questions/61977439/table-below-x-axis-in-ggplot

https://learnr.wordpress.com/2009/04/29/ggplot2-labelling-data-series-and-adding-a-data-table/