How to manually add a boxplot in a pre-existing ggplot2 line plot

126 Views Asked by At

I create a line plot with ggplot with the following data and code:


dat<-read.table(text= 
  "2019            2641.621           2613.385
  2020            2633.569           2605.428
  2021            2656.257           2627.863
  2022            2668.704           2640.147
  2023            2647.242           2618.982
  2024            2662.498           2634.032")

ggplot(dat, aes(x = V1))+
  
  geom_line(aes(y= V2),col="red") +
  geom_line(aes(y = V3),col="blue")

The resulting plot:

enter image description here

Now, I want to manually add a boxplot at x = 2025 by specifying boxplot values that I have previously calculated and are not in a data frame. I insert the code for the boxplot at the end:

ggplot(dat, aes(x = V1))+
  
  geom_line(aes(y= V2),col="red") +
  geom_line(aes(y = V3),col="blue") +
  
  geom_boxplot(
    stat = "identity",
    aes(x=2025,
        lower  = 2312.8,
        upper  = 2394.3,
        middle = 2343.5,
        ymin   = 2254.8,
        ymax   = 2440.4))

I get the following error:

Error in geom_boxplot(): ! Problem while converting geom to grob. ℹ Error occurred in the 5th layer. Caused by error in draw_group(): ! Can only draw one boxplot per group ℹ Did you forget aes(group = ...)?

I tried with geom_pointrange, and it does work:

ggplot(dat, aes(x = V1))+
  
  geom_line(aes(y= V2),col="red") +
  geom_line(aes(y = V3),col="blue") +
  geom_pointrange(aes(x=2025,y=2343.5,ymax=2394.3,ymin=2312.8),col="red")

enter image description here

But this is not what I want. How can I get the boxplot instead?

1

There are 1 best solutions below

0
Lucas On BEST ANSWER

Try this code:

ggplot()+geom_boxplot(data = data.frame(aux = c(2312.8,2394.3,2343.5,2254.8,2440.4)),
    aes(x=2110, y = aux))

If you create an auxiliar object, R can create the boxplot by itself without passing the other arguments. Also, try

ggplot()+geom_boxplot(data = data.frame(aux = c(2312.8,2394.3,2343.5,2254.8,2440.4)),
    aes(x=2110, y = aux), width = 10)

in order to increase its width and make it easier to see.