additional geom_point with ggplot group = variable

2019-08-04 13:52发布

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.

标签: r ggplot2
1条回答
手持菜刀,她持情操
2楼-- · 2019-08-04 14:21

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.

查看更多
登录 后发表回答