简体   繁体   中英

Making a trajectory plot using R

I want to make a trajectory plot of my data set, like a scatterplot of X,Y but the data points are connected with a line using an arrow (where the arrow points to the next position)

My data looks like this:

A    T   X     Y      V      GD  ND   ND2 TID
1 1 3.88 2.7 675.0 27.000  27.000  NA    NA  t1
2 1 3.92 2.7 677.7 42.691  69.691 2.7  7.29  t1
3 1 3.96 2.7 675.0 55.662 125.353 0.0  0.00  t1
4 1 4.00 2.7 675.0 55.662 181.015 0.0  0.00  t1
5 1 4.04 2.7 675.0 55.662 236.677 0.0  0.00  t1
6 1 4.08 2.7 680.4 42.691 279.368 5.4 29.16  t1

And I have tried using qplot to make it:

qplot(X, Y, data = sub.data1, color = TID, group = TID)+ 
  geom_line(linetype=5, size=1.5, arrow=arrow(angle=15, ends="both", type="closed"))+
  geom_point (shape=19, size=5, fill="black")

This was okay, it worked. Just that I wanted to make the points in my plot arrows that are pointing in the next data point. Any help would be great! Thanks!

I think you want to explore the geom_path and geom_segment attributes. See http://docs.ggplot2.org/current/geom_segment.html and http://docs.ggplot2.org/current/geom_path.html

For example, I can take your plot and simply change the line to a path to connect the dots in the order that they are presented in your table rather than by the X axis:

library("ggplot2")
library(grid) # needed for arrow function
library(data.table)
# see http://docs.ggplot2.org/current/geom_segment.html
df <- data.frame(a=c(1,2,3,4,5,6),T=c(3.88,3.92,3.96,4.00,4.04,4.08),X=c(2.7,2.9,2.7,2.0,2.7,2.0),Y=c(675.0,600.7,675.0,690.0,675.0,680.4),V=c(27.0,42,55,55,55,42),GD=c(27,70,125,181,236,279),ND=c(NA,2.7,0,0,0,5.4),ND2=c(NA,7,0,0,0,29.2),TID="t1")
qplot(X, Y, data = df, color = TID, group = TID)+ 
        geom_path(linetype=5, size=1.5, arrow=arrow(angle=15, ends="both", type="closed"))+
        geom_point (shape=19, size=5, fill="black")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM