Search code examples
rggplot2summary

How to get manual order or x-axis in ggsummarytable


Got the order in ggboxplot right (first Pre than Post), but can't get it to work in the ggsummarytable (also tried order with asc. and desc.). I added a short reproducible example.

Pre <- runif(50, 5.0, 7.5)
Post <- runif(50,6.5,10)
pre_string <- rep("Pre", times = length(Pre))
post_string <- rep("Post", times = length(Post))

data_merge<-c(Pre,Post)
prepost_merge<-(c(pre_string,post_string))
prepost_merge<-as.factor(prepost_merge)


df<-data.frame(data_merge)
df$group <- prepost_merge
head(df, 2)

# CREATE TABLE #
summary.stats <- df %>%
  group_by(group) %>%
  get_summary_stats(type = "full")

summary.plot <- ggsummarytable(
  summary.stats, x = "group", y = c("n", "median", "q1","q3"),variablename="", order = (c("Pre","Post")),
  ggtheme = theme_bw(),axis.line.x = element_blank(), axis.line.y = element_blank(),label_value = "",legend="none",
) + theme_pubr(
  base_size = 8,
  base_family = "",
  border = TRUE,
  margin = TRUE,
  x.text.angle = 0
)  + labs(x="",y="")

Reproducible example -

enter image description here

wrong order (needs to be pre post)

enter image description here


Solution

  • Like ggplot2 , ggsummarytable also can be sorted based on the factor levels.

    library(ggpubr)
    
    #Give the factor levels in the order that you want
    summary.stats$group <- factor(summary.stats$group, c('Pre', 'Post'))
    
    
    ggsummarytable(
      summary.stats, x = "group", y = c("n", "median", "q1","q3"),
      variablename="", order = (c("Pre","Post")),
      ggtheme = theme_bw(),
      axis.line.x = element_blank(), 
      axis.line.y = element_blank(),
      label_value = "",legend="none",
    ) + theme_pubr(
      base_size = 8,
      base_family = "",
      border = TRUE,
      margin = TRUE,
      x.text.angle = 0
    )  + labs(x="",y="")
    

    enter image description here