Home > Enterprise >  Errormessages for Boxplots with jitter strips (ggplot2)
Errormessages for Boxplots with jitter strips (ggplot2)

Time:01-31

I am trying to make boxplots with jitter strips using code from a website (Sampledata

Website example code I am trying to use

Sample data:

structure(list(pseudonym = c(1L, 2L, 4L, 5L, 6L, 7L, 3L, 8L, 
9L, 10L, 11L, 1L, 2L, 4L, 5L, 6L, 7L, 3L, 8L, 9L, 10L, 11L, 1L, 
2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), control.0.1. = c(0L, 0L, 0L, 
0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 
1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), intervention.0.1. = c(1L, 
1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 
0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), visit = c(2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), weight.V1.3 = c(60L, 
60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 59L, 59L, 59L, 
59L, 59L, 59L, 59L, 59L, 59L, 59L, 59L, 57L, 57L, 57L, 57L, 57L, 
57L, 57L, 57L, 57L)), class = "data.frame", row.names = c(NA, 
-31L))

CodePudding user response:

Your code has a lot of issues and syntax errors. Just to mention a few:

  1. A ggplot always starts with ggplot(). df %>% geom_boxplot(..) will not work.

  2. There is no data aesthetic. To tell ggplot2 which dataset to use you have to pass it to the data argument, e.g. do ggplot(data = df) or short ggplot(df).

  3. Doing scale_color_manual(values = weight_v1_3) does not work either. You don't have to pass the column name by which you want to color the plot (this is done inside aes()). Inside scale_color_manual you specify which colors to use.

  4. Finally, the g in the code you referenced is a ggplot object, i.e. you could assign a ggplot object to a variable. Then add additional layers to this object.

  5. Before going on I would suggest to work through a ggplot2 tutorial first to get the basics, e.g. the author of the post you referenced has a nice tutorial: https://www.cedricscherer.com/2019/08/05/a-ggplot2-tutorial-for-beautiful-plotting-in-r/

Note: I also did some minor data wrangling steps like renaming your columns and adding a groupci column.

library(ggplot2)
library(dplyr)

df <- df %>% 
  rename_with(~ gsub("\\.", "_", tolower(.x))) %>% 
  mutate(groupci = ifelse(control_0_1_ == 1, "control", "intervention"))

pal <- c("red", "blue")

g <- ggplot(df, aes(x = groupci, y = weight_v1_3))  
  geom_boxplot(aes(fill = groupci, fill = after_scale(colorspace::lighten(fill, .7))), alpha = .5, size = 1.5, outlier.size = 5)

g   
  geom_jitter(aes(color = groupci), width = .1, size = 7, alpha = .5)  
  scale_y_continuous(breaks = 1:9)  
  scale_color_manual(values = pal, guide = "none")  
  scale_fill_manual(values = pal, guide = "none")

  •  Tags:  
  • Related