使用manipulate()时如何突出显示兴趣点?

时间:2015-07-15 12:07:02

标签: r plot interactive

我正在尝试使用R生成的交互式图表向我的学生展示如何更改上升和运行会影响线的斜率。我基本上用以下代码完成了这个,但我想找到一种方法来突出显示点(x_1,y_1),(x_2,y_2):

manipulate(
   plot(x<-seq(from = -3,
          to = 3, 
          by = .02), 
   y=(y_2-y_1/(x_2-x_1))*x, 
   type = "l", 
   ylim = c(-5,5), 
   panel.first = grid()), 
y_2=slider(min = -3, 3, initial = 1, step = .5),
y_1=slider(min = -3, 3, initial = 0, step = .5),
x_2=slider(min = -3, 3, initial = 1, step = .5),
x_1=slider(min = -3, 3, initial = 0, step = .5)
)

感谢您提供的任何帮助

2 个答案:

答案 0 :(得分:0)

manipulate()的第一个参数是每次更改参数时(重新)计算的表达式。您可以将其作为一个支撑块来评估多个语句,这将允许在主plot()调用之后绘制其他点。以下是我将如何做到这一点:

library('manipulate');
manipulate(
    {
        x <- seq(-3,3,.02);
        y <- y_2-y_1/(x_2-x_1)*x;
        plot(x,y,type='l',ylim=c(-5,5),panel.first=grid());
        col <- 'red';
        points(x[c(1,length(x))],y[c(1,length(y))],pch=21,cex=1.5,col=col,bg=col);
    },
    y_2=slider(-3,3,1,step=.5),
    y_1=slider(-3,3,0,step=.5),
    x_2=slider(-3,3,1,step=.5),
    x_1=slider(-3,3,0,step=.5)
);

plot-with-points

(如果您对R语言中支撑块的含义有更深入的了解,请参阅我对What is "{" class in R?的回答。)

答案 1 :(得分:0)

修改@ bgolst的答案有助于创建以下代码,该代码突出显示输入(x_1,y_1),(x_2,y_2)值,而不仅仅是端点。我非常感谢他或她的意见

manipulate(
 {plot(x<-seq(from = -3,
          to = 3, 
          by = .02), 
   y=(y_2-y_1/(x_2-x_1))*x, 
   type = "l", 
   ylim = c(-5,5),
   panel.first = grid());
col <- 'red';
points(x_2,y = (y_2-y_1/(x_2-x_1))*x_2,pch=21,cex=1.5,col=col,bg=col);
col <- 'blue';
points(x = x_1,y = (y_2-y_1/(x_2-x_1))*x_1,pch=21,cex=1.5,col=col,bg=col);
},
y_2=slider(min = -3, 3, initial = 1, step = .5),
y_1=slider(min = -3, 3, initial = 0, step = .5),
x_2=slider(min = -3, 3, initial = 1, step = .5),
x_1=slider(min = -3, 3, initial = 0, step = .5)
)