我将点与笛卡尔坐标系中的线段相连。我通过将点循环到线段而陷入困境,因此,如果要更改它们,则不必每次都输入点和线段的坐标。 for循环可能会在这里有所帮助。
x <- -10:10
y <- -10:10
plot(x, y, type = "n", xlab = NA, ylab = NA, axes = FALSE);
axis(1, pos = 0, at = seq(-10, 10, by = 1), las=1, cex.axis=0.5)
axis(2, pos = 0, at = seq(-10, 10, by = 1), las=2, cex.axis=0.5)
points(2,1, col = "blue", pch = 20)
points(5,7, col = "blue", pch = 20)
points(-3,8, col = "green", pch = 20)
points(8,3, col = "green", pch = 20)
segments(2, 1, 5 , 7)
segments(-3, 8, 8, 3)
答案 0 :(得分:1)
您正在重复绘制点并绘制连接它们的线段的代码。在这些情况下,最好编写一个函数并在需要时调用它。
请注意函数参数pcol
,代表point color
,scol
代表segment color
。
connectPoints <- function(x, y, pcol, pch = 20, scol = "black"){
points(x[1], x[2], col = pcol, pch = pch)
points(y[1], y[2], col = pcol, pch = pch)
segments(x[1], x[2], y[1], y[2], col = scol)
}
plot(x, y, type = "n", xlab = NA, ylab = NA, axes = FALSE);
axis(1, pos = 0, at = seq(-10, 10, by = 1), las=1, cex.axis=0.5)
axis(2, pos = 0, at = seq(-10, 10, by = 1), las=2, cex.axis=0.5)
x1 <- c(2, 1)
y1 <- c(5, 7)
x2 <- c(-3, 8)
y2 <- c(8, 3)
connectPoints(x1, y1, pcol = "blue")
connectPoints(x2, y2, pcol = "green")
答案 1 :(得分:0)
使用该功能可以分割所需的任何点:
myplot<-function(x1=sample(20),y1=sample(20),axis_range=20){
x <- -axis_range:axis_range
y <- -axis_range:axis_range
plot(x, y, type = "n", xlab = NA, ylab = NA, axes = FALSE);
axis(1, pos = 0, at = seq(-axis_range, axis_range, by = 1), las=1, cex.axis=0.5)
axis(2, pos = 0, at = seq(-axis_range, axis_range, by = 1), las=2, cex.axis=0.5)
cols<-sample(colors(),ceiling(length(x1)/2))
for (i in 1:length(x1)) {
points(x1[i],y1[i],col = cols[ceiling (i/2)], pch = 20)
}
for (j in 1:floor((length(x1)/2))) {
segments(x1[(2*(j-1))+1],y1[(2*(j-1))+1],x1[2*j],y1[2*j])
}
}
myplot(x1=sample(20),y1=sample(20),axis_range=20)