[R] Plot trajectories using ggplot?

Mike Smith mike at hsm.org.uk
Sat May 14 19:29:05 CEST 2016


Thanks very much for the pointer - that was spot on. The key thing was to add

df$case <- rownames(df)

to generate the row by row case for when I melted the columns. As Ive since found out either of these will work

ggplot(ds, aes(x = as.numeric(variable), y = value, colour = case)) +
  geom_point () + geom_line()

ggplot(ds, aes(x = variable, y = value, group = case)) +
  geom_point () + geom_line()

Much appreciated!

Saturday, May 14, 2016, 10:13:15 AM, you wrote:

US> You can introduce the row number as a  case number, you can group
US> by case and plot the connecting lines


US> #Read raw data
US> df =
US> read.table("http://www.lecturematerials.co.uk/data/sample.csv",
US> header=TRUE, sep=",", dec=".", na.strings=c("NA"))
US> names(df)<-c("1","2","3","4")
US> df$case <- rownames(df)


US> #Turn data from wide to long
US> ds<-melt(df, id.vars = "case")


US> ggplot(ds, aes(x = variable, y = value, group = case)) +
US>   geom_point () + geom_line()


US> Hope this helps,
US> Ulrik
US> On Sat, 14 May 2016 at 10:20 Mike Smith <mike at hsm.org.uk> wrote:

US> Hi
US>  
US>  Ive got stuck using the code below to try to plot trajectories -
US> columns are data recorded at time points, rows are cases. Ive used
US> melt to turn the data long allowing me to group by time point and
US> then plot using geom_point but I now need to join the points based
US> upon the correct case (i.e. the first row in the original
US> dataset). geo_segment allows me to specify start-end but I need to
US> do this over multiple time periods....
US>  
US>  Any help much appreciated
US>  
US>  thanks
US>  
US>  mike
US>  
US>  
US>  library(reshape2)
US>  library(ggplot2)
US>  library(ggthemes)
US>  library(cowplot)
US>  
US>  #Read raw data
US>  df =
US> read.table("http://www.lecturematerials.co.uk/data/sample.csv",
US> header=TRUE, sep=",", dec=".", na.strings=c("NA"))
US>  names(df)<-c("1","2","3","4")
US>  
US>  #Turn data from wide to long
US>  ds<-melt(df)
US>  
US>  ggplot(ds, aes(x = variable, y = value)) +
US>         geom_point (shape=19, size=5, fill="black")
US>  
US>  
US>  
US>  ---
US>  Mike Smith
US>  
US>  ______________________________________________
US>  R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
US>  https://stat.ethz.ch/mailman/listinfo/r-help
US>  PLEASE do read the posting guide
US> http://www.R-project.org/posting-guide.html
US>  and provide commented, minimal, self-contained, reproducible code.
US>  


---
Mike Smith



More information about the R-help mailing list