2

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 Answer 1

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'))
Sign up to request clarification or add additional context in comments.

2 Comments

Dear @MrGumble, thank you very much for the hint! I created a separate file for the "optimal" values and it worked out!
You're welcome! But for future reference, please make a minimal working example (stackoverflow.com/help/mcve) - you are almost there with code and expected output! It's really difficult to extract the data from an image. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.