Home > Back-end >  R. How can I add a second plot to a ggplot AFTER the original plot is created?
R. How can I add a second plot to a ggplot AFTER the original plot is created?

Time:01-03

I am creating a simple ggplot (p <- ggplot(Data) geom_line(aes(x, y)). I would like to plot a second line on the same ggplot, but do not have the data available when the original ggplot is made. Is there a way to add the second plot after the first plot has been completed?

Put another way, when using plot and lines to create simple charts, you can do stuff between creating the plot then creating the line. In ggplot, it seems you have to create both lines at the same time. How can I use ggplot to create the first plot, do other stuff, then come back and add a second plot using ggplot?

I've tried suggested solutions like this, but they do not work.

p <- ggplot(Data)  
  geom_line(aes(x, y)) 


p<-p geom_line(Data,aes(x,z))

CodePudding user response:

Here's an example making one plot and adding another afterwards with new data.

As @stefan noted, the expected order for additional geoms is to have data after aesthetics, but you can put the data first if you specify it like data = <NEW DATA>, ...

p <- ggplot(mtcars)  
  geom_line(aes(mpg, wt))

p   geom_point(data = data.frame(mpg = 10:30, wt = seq(2,5, length.out = 21)),
               aes(mpg, wt))

Last line equivalent to:

p   geom_point(aes(mpg, wt),
               data.frame(mpg = 10:30, wt = seq(2,5, length.out = 21)))

enter image description here

CodePudding user response:

What you're trying to do is indeed possible:

g <- ggplot(mtcars)  
  geom_line(aes(x=mpg, y=hp), col='red')

print(g)

enter image description here

g2 <- g  
  geom_line(aes(x=mpg, y=qsec), col='blue')
print(g2)

enter image description here

CodePudding user response:

Yes, you can add additional layers to an existing ggplot object by using the operator and adding a new layer with the geom_line function. Here's an example of how you could do this:

Create the initial plot with one line

p <- ggplot(Data) geom_line(aes(x, y))

Do other stuff here

Add a second line to the plot

p <- p geom_line(Data, aes(x, z)) You can also use other geoms, like geom_point or geom_bar, to add additional data to the plot. Just make sure to add the new layer to the existing ggplot object using the operator.

p <- p geom_point(Data, aes(x, w)) I hope this helps! Let me know if you have any questions.

  • Related