noLongerRandom
noLongerRandom

Reputation: 531

Drawing line segments in R

I've got some x and y coordinates that I am trying to plot into line segments. And I'm getting some unexpected behavior from what I think should work.

For each segment, there is a starting set of coordinates (x1,y1) and an ending set of coordinates (x2,y2). It's a data frame (call it 'df') that looks like this:

  x1   y1   x2   y2
34.9 67.9 62.5 68.8
66.8 80.9 58.8 88.4
58.8 88.4 66.0 68.4
64.0 65.8 56.2 62.6
56.2 62.6 56.6 75.3
54.5 70.0 72.9 51.3

The segments are not necessarily continuous. By that I mean sometimes the ending x,y of one segment is the starting point of the next segment; other times it is not.

So I try to plot them

lines(c(df$x1, df$x2), c(df$y1, df$y2))

And I get the following, which is not at all what I want. There are extra segments being drawn and they are all coming out connected. And it's just wrong. It looks like it's plotting 11 or 12 segments from 6 sets of start/end points.

bad plot

Now, I can step through and plot them one at a time:

lines(c(df$x1[1], df$x2[1]), c(df$y1[1], df$y2[1]))
lines(c(df$x1[2], df$x2[2]), c(df$y1[2], df$y2[2]))
lines(c(df$x1[3], df$x2[3]), c(df$y1[3], df$y2[3]))
Etc.

I get the plot below, which is what I'm after. good lines So can someone help explain what it happening in the first instance that makes it different from the second? And is there a way to do this all in one line without having to step through or write a function that loops through?

Upvotes: 4

Views: 22632

Answers (1)

Spacedman
Spacedman

Reputation: 94192

The segments function is what you are looking for:

> data
    x1   y1   x2   y2
1 34.9 67.9 62.5 68.8
2 66.8 80.9 58.8 88.4
3 58.8 88.4 66.0 68.4
4 64.0 65.8 56.2 62.6
5 56.2 62.6 56.6 75.3
6 54.5 70.0 72.9 51.3
> plot(range(data$x1,data$x2), range(data$y1, data$y2),type="n")
> segments(data$x1, data$y1, data$x2, data$y2)

Note you have to set the plot up first. You might want to do:

> plot(NA, xlim=c(0,100), ylim=c(0,100), xlab="x", ylab="y")
> segments(data$x1, data$y1, data$x2, data$y2)

to get the bounds in your figure.

segments

Upvotes: 11

Related Questions