Home > OS >  Problem with boxplot: flat lines in function creation
Problem with boxplot: flat lines in function creation

Time:02-15

I have a problem with this function (i am new on R)

I want to create a simple function in which insert a gene(variable) to obtain a simple boxplot to compare two conditions (condition), but i obtain two flat lines and dont' know why. In the function i want to have "condition" on x axis and the value of variable on y axis, and i remove initially na values from the df, but i don't think that was the problem.

    funzione <- function(variabile) {
    
    tab <- tab_n %>% filter(!is.na(Condition))
    tab %>% ggplot(aes(x = Condition, y = variabile, fill = Condition))   
    geom_boxplot(alpha = 0.5)  
    geom_point(position = position_dodge(width=0.75)) 
    ggpubr::stat_compare_means(aes(group = Condition), label.x.npc = "center", size = 3.2)  
    theme_bw()
}

Here are the first lines of the database I have.

Gender Condition variable_to_insert
Male cond_1 5.6
Female cond_1 4.7
Female cond_2 4.8
Female cond_1 5.8
Male cond_2 5.1
Female cond_1 5.5
Male cond_2 7.9
Male cond_2 7.1
Female cond_1 2.9

CodePudding user response:

The function below is rewritten to accept a data.frame and a variable as arguments.

library(dplyr)
library(ggplot2)

funzione <- function(x, variabile) {
  x %>% 
    filter(!is.na(Condition)) %>%
    ggplot(aes(x = Condition, y = {{variabile}}, fill = Condition))   
    geom_boxplot(alpha = 0.5)  
    geom_point(position = position_dodge(width=0.75))   
    ggpubr::stat_compare_means(aes(group = Condition), label.x.npc = "center", size = 3.2)  
    theme_bw()
}

tab_n %>% funzione(variable_to_insert)

Created on 2022-02-14 by the reprex package (v2.0.1)

Data

tab_n <- read.table(text = "
Gender  Condition   variable_to_insert
Male    cond_1  5.6
Female  cond_1  4.7
Female  cond_2  4.8
Female  cond_1  5.8
Male    cond_2  5.1
Female  cond_1  5.5
Male    cond_2  7.9
Male    cond_2  7.1
Female  cond_1  2.9
", header = TRUE)

Created on 2022-02-14 by the reprex package (v2.0.1)

  • Related