Plotting and manipulating a graph in R

Viewed 59

The goal is: Write and test a function that draws a triangle with coordinates by default(100,100); (200,100); (150,200). Using the control parameters, implement the movement of the point that defines one of the corners of the triangle, left-right, up-down. If I understood the problem correctly, with the change in the position of the point, the position of the other points remains unchanged. I tried to write(I leave my code below):

triangle <- function(p1, p2, p3, x.l=0, x.r=0,x.d=0,x.u=0) {
  
  
 
  #move the point left-right
  p1[1]<-p1[1]+x.l
  p2[1]<-p2[1]+x.r
  #moving the point up and down
  p1[2]<-p1[2]+x.u
  p2[2]<-p2[2]-x.d
  
  x <- c(p1[1]:p2[1])
  y.up <- 0 #the upper part of the triangle
  
  for (i in x) {
    #we calculate the value of y on the left side-according to the formula of a straight line passing through 2 given points
    
    if (i <= p3[1]) {
      y.up[i] <- p1[2] + (p3[2] - p1[2]) / (p3[1] - p1[1]) * (i - p1[1])
    }
    
    #----------we count the values of y on the right side
    if (i > p3[1]) {
      y.up[i] <- p2[2] + (p3[2] - p2[2]) / (p3[1] - p2[1]) * (i - p2[1])
    }
  }
  y.up <- y.up[p1[1]:length(y.up)]
  #draw the upper part of the triangle
  plot(
    x = x,
    y = y.up,
    type = 'l',
    col = 'red',
    lwd = 2
  )
  
  #lower part
  y.bottom <- rep(p1[2], length(x))
  
  lines(
    x = x,
    y = y.bottom,
    type = 'l',
    col = 'red',
    lwd = 2
  )
  
} 
  #checking the function operation
  p1 <- c(100, 100)
  p2 <- c(200, 100)
  p3 <- c(150, 200)


triangle(p1, p2, p3, x.l=0, x.r=0,x.u=0,x.d=0)

Unfortunately, as a result, my triangle shape disappears and some kind of broken line is obtained. What is the reason for this?

0 Answers
Related