1

Is it possible to include group = variable and add another point in ggplot.

For example:

require(MuMIn)
require(ggplot2)

data(Cement)
d <- data.frame(Cement)
dd <- melt(d,id.var = "y")
d2 <- runif(length(dd[,1]))
d2 <- data.frame(first = dd$y,
                 second = d2)

ggplot(dd, aes(x = y,y = value,group = variable)) + 
  geom_line() + 
  geom_point(data = d2,aes(x = first,y = second))

This leads to an error. Eventually I would like to add the points specified here onto the line plot.

1 Answer 1

6

Mapped aesthetics in ggplot2 follow a sort of inheritance pattern. When you map aesthetics at the "top" level, in ggplot(), they are automatically passed down to all subsequent layers.

This means that geom_point is looking for a variable column in d2. It won't look for y or value columns, since you explicitly re-mapped the x and y aesthetics in geom_point().

The solution is either to move the top level aesthetic mappings from ggplot() to geom_line(), or to un-map group in geom_point using group = NULL.

Additionally, Didzis pointed out a third solution in the comments, which is to add inherit.aes = FALSE to geom_point.

Sign up to request clarification or add additional context in comments.

1 Comment

Third solution would be to add inherit.aes=FALSE to geom_point() call

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.