1

I am trying to plot a line and a dot using ggplot2. I looked at but it assumes the same dataset is used. What I tried to do is

library(ggplot2)

df = data.frame(Credible=c(0.2, 0.3),
                 len=c(0, 0))

zero=data.frame(x0=0,y0=0)

 ggplot(data=df, aes(x=Credible, y=len, group=1)) +
  geom_line(color="red")+
  geom_point()+
  labs(x = "Credible", y = "")

  ggplot(data=zero, aes(x=x0, y=y0, group=1)) +
  geom_point(color="green")+
  labs(x = "Credible", y = "")

but it generates just the second plot (the dot).

Thank you

user552231
  • 1,095
  • 3
  • 21
  • 40
  • https://stackoverflow.com/questions/7476022/geom-point-and-geom-line-for-multiple-datasets-on-same-graph-in-ggplot2?rq=1 – CMichael Jul 09 '21 at 12:55

1 Answers1

1

Given the careful and reproducible way you created your question I am not just referring to the old answer as it may be harder to transfer the subsetting etc.

You initialize a new ggplot object whenever you run ggplot(...).

If you want to add a layer on top of an existing plot you have to operate on the same object, something like this:

ggplot(data=df, aes(x=Credible, y=len, group=1)) +
  geom_line(color="red")+
  geom_point()+
  labs(x = "Credible", y = "") +
  geom_point(data=zero, color="green", aes(x=x0, y=y0, group=1))

Note how in the second geom_point the data source and aesthetics are explicitly specified instead to prevent them being inherited from the initial object.

CMichael
  • 1,856
  • 16
  • 20