2
votes

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:

Ggplot with dots

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:

  1. Ggplot without dots : Grouped boplot

  2. 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

1 Answers

1
votes

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'))