在R中绘制线段 [英] Drawing line segments in R

查看:340
本文介绍了在R中绘制线段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些x和y坐标,它们正试图绘制成线段.我从我认为应该有效的方法中得到了一些意想不到的行为.

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.

对于每个段,都有一组起始坐标(x1,y1)和一组结束坐标(x2,y2).这是一个数据帧(称为"df"),如下所示:

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

段不一定是连续的.我的意思是有时一个片段的结尾x,y是下一个片段的起点;有时候不是.

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.

所以我尝试绘制它们

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

我得到以下内容,这根本不是我想要的.绘制了额外的线段,它们全部连接在一起.这是错误的.看起来好像是从6组起点/终点绘制11或12个线段.

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.

现在,我可以一步一步地绘制它们:

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. 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?

推荐答案

segments函数是您要寻找的:

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

获取您的图形范围.

这篇关于在R中绘制线段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆