避免改变ggplot

时间:2016-11-13 17:42:54

标签: r ggplot2

问题。有没有办法在ggplot中避免以下行为?

x=c(1,3,4,5,6)
y=c(0.5,2,3,7,1)
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

绘图上的绘图仍然固定在输入中给出的数值的值上。我是否必须创建其他变量来存储坐标?

问2.如何在ggplot中绘制polygonal chain

n=length(x)-1
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
for (i in 1:n){
  p <-p + geom_segment(aes(x = x[i], y = y[i], xend = x[i+1], yend = y[i+1]), colour = "red")
  p$plot_env <- list2env(list(x=x,y=y))
  }

在这里回答:Drawing polygonal chains in ggplot

1 个答案:

答案 0 :(得分:0)

这似乎是一个黑客但显然有效:在修改x之前,请执行

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

然后

x[1] <- 10
p

保持情节不变。