user3083324 user3083324 - 27 days ago 7
R Question

Avoid changing ggplot

Is there a way of avoiding the following behavior in a ggplot?

x=c(1,3,4)
y=c(0.5,2,3)
n=2
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <-p + geom_segment(aes(x = x[1], y = y[1], xend = x[2], yend = y[2]), colour = "red")
p <-p + geom_segment(aes(x = x[2], y = y[2], xend = x[3], yend = y[3]), colour = "red")
p


enter image description here

x[1]=10
p


enter image description here

The drawing on the plot remains anchored to the value of the numeric values given in input. Do I have to create other variables for storing the coordinates?

Answer

This seems like a hack but apparently works: before modifying x, do

p$plot_env <- list2env(list(x=x,y=y))

Then

x[1] <- 10
p

leaves the plot unchanged.