问题
I created a grouped boxplot with ggplot2. Now I want to add additional data to the existing plot in the following way: for each month I have one "Optimal" value that should be displayed as a dot and these dots should be connected by a line. This is the desired state:

How could I add those dots and lines to my plot? Can I by any chance put the connecting lines behind the boxplots?
Here is my current state and the data:
Ggplot without dots :
Data frame:Data frame
R Code:
data("MyData")
MyData$Month <- as.factor(MyData$Month)
head(MyData)
MyPlot <- ggplot(MyData, aes(x=Month, y=Note, fill=Treatment)) +
geom_boxplot()
MyPlot
Thank you in advance!
回答1:
Simply add an geom mapping the y to a different variable. For the sake of simplicity, I moved some of the aesthetics to the geom_boxplot.
MyPlot <- ggplot(MyData, aes(x=Month)) + geom_boxplot(aes(y=Note, fill=Treatment)
MuPlot <- MyPlot + geom_pointline(aes(y=Optimum), colour="green", stroke="black")
This will however not add you points to the legend, as ggplot2 does not support multiple encodings of the same scale (i.e. using both Treatment and a separate variable for colour).
The geom geom_pointline
is from the 'lemon' package.
On a second note, try this for the second line:
MuPlot <- MyPlot + geom_pointline(aes(y=Optimum, colour="Optimum"), stroke="black") + scale_colour_manual(values('Optimum'='green'))
来源:https://stackoverflow.com/questions/53153701/ggplot-adding-new-data-to-the-existing-grouped-boxplot