Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Lines connecting two points in R

Is there any way to create lines in R connecting two points? I am aware of lines(), function, but it creates line segment what I am looking for is an infinite length line.

like image 360
Udayan Maurya Avatar asked Jan 07 '16 14:01

Udayan Maurya


People also ask

How do you add a line to a point in R?

abline() function in R Language is used to add one or more straight lines to a graph. The abline() function can be used to add vertical, horizontal or regression lines to plot. Syntax: abline(a=NULL, b=NULL, h=NULL, v=NULL, …)

What does line () do in R?

lines() function in R Programming Language is used to add lines of different types, colors and width to an existing plot.

How do you draw a line in R programming?

To draw a line plot in R, call plot() function and along with the data to plot, pass the value “l” for “type” parameter. In this tutorial, we will learn how to use plot() function to draw line plot, with example programs.

How to draw a line segment between two points in R?

segment () function in R Language is used to draw a line segment between to particular points. x, y: coordinates to draw a line segment between provided points. Here, x0 & y0 are starting points of the line segment and x1 & y1 are ending points of line segment . Example 3: Draw multiple line segments to R Plot.

How to draw a basic line plot in R?

In the examples of this R tutorial, we’ll use the following example data: Our data consists of two numeric vectors x and y1. The vector x contains a sequence from 1 to 10, y1 contains some random numeric values. If we want to draw a basic line plot in R, we can use the plot function with the specification type = “l”.

How to join points with lines in ggplot2?

Hence, data analyst or researcher try to visualize this type of graph by joining the points with lines. In ggplot2, this joining can be done by using geom_line () function.

How to draw connection lines between several locations on a map?

This post explains how to draw connection lines between several locations on a map, using R. Method relies on the gcIntermediate function from the geosphere package. Instead of making straight lines, it draws the shortest routes, using great circles.


Video Answer


2 Answers

Here's an example of Martha's suggestion:

set.seed(1)
x <- runif(2)
y <- runif(2)

# function
segmentInf <- function(xs, ys){
  fit <- lm(ys~xs)
  abline(fit)
}

plot(x,y)
segmentInf(x,y)

enter image description here

like image 87
Marc in the box Avatar answered Oct 01 '22 13:10

Marc in the box


#define x and y values for the two points
x <- rnorm(2)
y <- rnorm(2)
slope <- diff(y)/diff(x)
intercept <- y[1]-slope*x[1]
plot(x, y)
abline(intercept, slope, col="red")
# repeat the above as many times as you like to satisfy yourself
like image 38
doctorG Avatar answered Oct 01 '22 15:10

doctorG