ggplot2线图顺序 [英] ggplot2 line plot order

查看:191
本文介绍了ggplot2线图顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列的订购点,如下所示:


然而,当我尝试用一​​条线连接点时,我得到以下输出:

这个图连接26到1和25到9和10(一些错误),而不是按照顺序。绘制点的代码如下:

  p <-ggplot(aes(x = x,y = y), data = spat_loc)
p <-p + labs(x =x Coords(Km),y =Y coords(Km))+ ggtitle(Locations)
p <-p + geom_point(aes(color =Red,size = 2))+ geom_text(aes(label = X))
p + theme_bw()

为了绘制这条线,我只是使用:
p + geom_line((aes(x = x,y = y)),color =blue)+ theme_bw()



包含位置的文件具有以下结构:

  X xy 
1 210 200



其中X是数字ID,x和y是一对坐标。



我需要做些什么才能使这一行遵循点的顺序?

解决方案

geom_path()将以原始顺序连接点,因此您可以按照您希望连接的方式对数据进行排序,然后执行 + geom_path()。这里有一些虚拟数据:

$ $ p $ dat < - data.frame(x = sample(1:10),y = sample( 1:10),order = sample(1:10))
ggplot(dat [order(dat $ order),],aes(x,y))+ geom_point()+ geom_text(aes(y = y + 0.25,label = order))+
geom_path()


I have a series of ordered points as shown below:

However when I try to connect the points by a line, I get the following output:

The plot is connecting 26 to 1 and 25 to 9 and 10 (some of the errors), instead of following the order. The code for plotting the points is given below:

p<-ggplot(aes(x = x, y = y), data = spat_loc)
p<-p + labs(x = "x Coords (Km)", y="Y coords (Km)") +ggtitle("Locations")
p<-p + geom_point(aes(color="Red",size=2)) + geom_text(aes(label = X))
p + theme_bw()

And for plotting the line I am just using: p + geom_line((aes(x=x, y=y)),colour="blue") + theme_bw()

The file which contains the locations have the following structure:

X    x    y
1    210  200 
.
.
.

where X is the numeric ID and x and y are the pair of co-ordinates.

What do I need to do to make the line follow the ordering of points?

解决方案

geom_path() will join points in the original order, so you can order your data in the way you want it joined, and then just do + geom_path(). Here's some dummy data:

dat <- data.frame(x = sample(1:10), y = sample(1:10), order = sample(1:10))
ggplot(dat[order(dat$order),], aes(x, y)) + geom_point() + geom_text(aes(y = y + 0.25,label = order)) +
  geom_path()

这篇关于ggplot2线图顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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