1

I'm trying to use interactive plots generated with R to show my students how changing the rise and run affect a line's slope. I've basically done this with the following code, but I'd like to find a way to highlight the points (x_1, y_1), (x_2, y_2) as well:

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)
)

I appreciate any help that you can offer

user152265
  • 13
  • 3

2 Answers2

0

The first argument to manipulate() is an expression which is (re)evaluated every time the parameters are changed. You can make it a braced block to evaluate multiple statements, which will allow drawing additional points after the main plot() call. Here's how I would do this:

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

(See my answer to What is "{" class in R? if you're interested in more insight about the meaning of braced blocks in the R language.)

Community
  • 1
  • 1
bgoldst
  • 34,190
  • 6
  • 38
  • 64
0

modifying @bgolst's answer helped to create the following code, which highlights the input (x_1, y_1), (x_2, y_2) values, instead of just the endpoints. I am very grateful for his or her input

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)
)
user152265
  • 13
  • 3