Daniel González
Daniel González

Reputation: 15

Having trouble setting up correctly a boxplot with ggplot

I'm trying to set up a boxplot using ggplot. I have three temperature treatments along five days and want to create a boxplot where I can see the five days in the x-axis with three boxes in each day, representing each treatment. Here's a link to the image of the output: https://i.imgur.com/F61TfM5.png

By using the boxplot() function, I created a graph that is almost what I want, but I'm still looking to understand how can I do it with ggplot.

head() of the data I'm using is:

Tratamiento  Dias TotalLength
  <fct>       <dbl>       <dbl>
1 Control         1         261
2 Control         1         262
3 Control         1         366
4 Control         1         315
5 Control         1         351
6 Control         1         320

I uploaded the data to https://pastebin.com/raw/ZQk8tfK5

The code for the boxplot that showed me what I wanted to see is:

library(RColorBrewer)
TLboxplot <- boxplot(TotalLength ~ Tratamiento + Dias, data= TLmeasure, 
    main = 'Total Length', 
    xlab = "Tratamiento x Dias", ylab = "TL",
    ylim = c(100,700),
    col= brewer.pal(n = 3, name = "Reds"))

The code I used for ggplot that is not what I'm looking for is:

library(ggplot2)
TLggplot <- ggplot(TLmeasure, aes(x=Tratamiento, y=TotalLength, 
fill=Tratamiento)) + 
  labs(title="Total Length", x="Temperatura x Dia", y="TL(µm)") +
  geom_boxplot() + 
  scale_fill_brewer(palette="Reds") +
  theme_classic() +
  theme(legend.position = "top")

The actual result of the ggplot is a graph with 3 boxes and each treatment in the x-axis instead of the 5 days and 3 boxes per day. What I'm looking for is only one graph with 15 boxes, three per day of each treatment. Here's a link to an image of the correct boxplot with boxplot(): https://imgur.com/EwGD1ES.png

Regarding the boxplot() right up there, I think that the temperature should be nested to the day so that it shows three boxes in only one tick. I'm not sure if I'm making myself clear with this statement...

This is my first question here. Hope it is detailed enough. Seems I'm having trouble with the images but I think the URL should work.

EDIT: Thank you for your answer, @r_alanb ! It worked for me.

Upvotes: 0

Views: 63

Answers (1)

r_alanb
r_alanb

Reputation: 913

You were close.

You need to have Tratamiento as the fill, and Dias as a factor as x:

library(ggplot2)
library(RColorBrewer)

ggplot(TLmeasure, aes(as.factor(Dias), TotalLength, fill = Tratamiento)) +
  geom_boxplot() + 
  # the rest of your code
  labs(title="Total Length", x="Temperatura x Dia", y="TL(µm)") +
  geom_boxplot() + 
  scale_fill_brewer(palette="Reds") +
  theme_classic() +
  theme(legend.position = "top")

Results in the following:

boxplot of time vs. TotalLength by temperature group

Upvotes: 1

Related Questions