I have data with some dynamic measurements.
datadim=structure(list(group = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), dim1 = c(60L, 69L, 60L,
63L, 61L, 68L, 68L, 69L, 66L, 60L, 69L, 62L, 60L, 60L, 70L, 67L,
68L, 70L, 66L), dim2 = c(70L, 61L, 61L, 66L, 65L, 69L, 70L, 70L,
66L, 69L, 61L, 66L, 66L, 65L, 62L, 68L, 61L, 63L, 61L), dim3 = c(63L,
62L, 66L, 62L, 69L, 60L, 62L, 68L, 64L, 61L, 68L, 63L, 65L, 63L,
64L, 62L, 69L, 62L, 63L), dim4 = c(68L, 69L, 67L, 63L, 64L, 65L,
70L, 70L, 62L, 64L, 61L, 69L, 66L, 61L, 68L, 66L, 66L, 67L, 64L
)), class = "data.frame", row.names = c(NA, -19L))
I want create boxplots for this, with line for compare median for my focus group (group column).
I just use simple boxplot(datadim) but i didn't get needed line. I just get such.

I don't want such plots. I need plots like i created in paint
Where blue color is first group and red color is second group. I also signed in what places which descriptive statistics are displayed(95% confidence interval,max,min,median). Inside each group, for example the first, we see a blue line that passes through the median of each dimension, and similarly, inside the second group, the red line passes along the median of each dimension. But boxplot doesn't create it.
How using boxplot or ggplot2 get plots like i provided in my second picture where there is a line by medians for each group separately (blue and red lines)?
CodePudding user response:
You can use stat_summary in ggplot. To do this, you first need to convert your data to long format (here using tidyr::pivot_longer() and convert the group to a factor:
library(tidyr)
datadim.lng <- datadim %>% pivot_longer(-group,names_to="dim", values_to = "value")
datadim.lng$group <- as.factor(datadim.lng$group)
Then run the ggplot code:
ggplot(datadim.lng, aes(x = dim, y = value, fill = group))
geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)
theme_classic()
stat_summary(
fun = median,
geom = 'line',
aes(group = group, color = group),
position = position_dodge(width = 0.85)
)
Which gives:
If you want to change the color of the line, per your example:
ggplot(datadim.lng, aes(x = dim, y = value, fill = group))
geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)
theme_classic()
stat_summary(
fun = median,
geom = 'line',
aes(group = group, color = group),
position = position_dodge(width = 0.85)
)
scale_color_manual(values = c("red", "blue"))


