I am trying to make boxplots with jitter strips using code from a website (
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:
A ggplot always starts with
ggplot().df %>% geom_boxplot(..)will not work.There is no
dataaesthetic. To tell ggplot2 which dataset to use you have to pass it to thedataargument, e.g. doggplot(data = df)or shortggplot(df).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 insideaes()). Insidescale_color_manualyou specify which colors to use.Finally, the
gin 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.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")


