Boxplots spaced by age on x axis

Hi everyone, i could use some help. I'm trying to plot measurements from patients of various age in one boxplot, boxes by age. I don't have samples for every age, but i want x axis to just be ages 1-100 and boxes to apear wherever i have data.
I managed to put together regular boxplot graff, but i need help with the last part.
Here is my code.
data1 <- data.frame(measure=c(set1, set2 ,set3, set4))
ages <- rep(c(2,2, 18, 18, 24, 28, 37, 40, 41, 46, 55, 58, 61, 62, 77),each=4)
data2 <- cbind(data1,as.factor(ages))

ggplot(data = data2, aes(x=as.factor(ages), y=measure)) +
geom_boxplot() + geom_point() + geom_smooth(method = "lm", se=FALSE, color="black", aes(group=1))

(set1 contains one measurement for each patient, same for set2-3-4) They are ofcourse normalised.

One way would be to define ages as a factor in data2 and define the levels from 1 to 100. Then, in the plot, you no longer have to call as.factor(ages) (it was already done), and you can use scale_x_discrete(drop = F) to show all factor levels on the x-axis.

data2 <- cbind(data1, 
               ages = factor(ages, levels = 1:100)
               )

ggplot(data = data2, aes(x=ages, y=measure)) +
  geom_boxplot() + 
  geom_point() + 
  geom_smooth(method = "lm", se=FALSE, color="black", aes(group=1)) +
  scale_x_discrete(drop = F)

Thank you, it worked perfectly. I'm kind of new to R, so sorry if the question was trivial.

Excellent! No need to apologize. There's a lot to learn, and this a place we all get to do it...together! Keep on exploring, and welcome to the community!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.