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:
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")
But this is not what I want. How can I get the boxplot instead?


geom_xxxfunctions typically have aninherit.aesargument which can trip the unwary. To create your boxplot, try... + geom_boxplot(data=<yourboxplotdataframe>, inherit.aes=FALSE, ...). It's difficult to be more precise because your question is neither reproducible (you haven't given us test data) nor minimal (fills and colours are not relevant to the question). Also, I would avoidlimitsin ascalefunction. That can have undesiravle and confusing side effects.coord_cartesianis much safer.