Home > database >  removing zeros from a part of a ggpaired plot using ggplot_build
removing zeros from a part of a ggpaired plot using ggplot_build

Time:01-13

I want to remove zeros from only the violin part of this graph

I tried using the ggplot_build function but I don't get the desired outcome and somehow it removes the statistical test.

Am I doing something wrong? I attach code and picture of the problem

enter image description here

library(introdataviz)
library(ggpubr)
library(grid)

#set seed
set.seed(42)

#build dunny data
first <- sample(c(rep(0,100), rnorm(50,15,2)))
second <- sample(c(rep(0,100), rnorm(50,10,1)))
df <- data.frame(first, second)


# build plot
p1 <- ggpaired(df,cond1 = "first", cond2 = "second",line.color = "gray") 
   stat_compare_means(paired = TRUE) 
  introdataviz::geom_split_violin( trim = TRUE,alpha = .4)   ylim(0,22)
#create ggplot_build object
p1_build <- ggplot_build(p1)

#remove zeros from violin plot part
p1_build$data[[4]] <- subset(p1_build$data[[4]], first != 0 & second != 0)
p1_build$data[[5]] <- subset(p1_build$data[[5]], first != 0 & second != 0)

#produce new graph
p2 <- ggplot_gtable(p1_build)
grid.draw(p2)

CodePudding user response:

If you want to exclude the zeros from the violin plot it's probably easier to use a filtered dataset for geom_split_violin:

library(introdataviz)
library(ggpubr)
library(grid)

ggpaired(df, cond1 = "first", cond2 = "second", line.color = "gray")  
  stat_compare_means(paired = TRUE)  
  introdataviz::geom_split_violin(
    data = ~ subset(.x, first != 0 & second != 0), 
    trim = TRUE, alpha = .4
  )  
  ylim(0, 22)

enter image description here

  • Related