0

I've written something in R using ggplot2 and don't know why it behaves as it does.

If I plot my data using geom_point and geom_line it is supposed to draw lines trough those points. but instead of connecting all the points it only connects those that are on a horizontal line. I don't know how to handle this.

This is a simple version of the code:

date<-c("2014-07-01","2014-07-02","2014-07-03",
    "2014-07-04","2014-07-05","2014-07-06",
    "2014-07-07")
mbR<- c(160,163,169,169,169,169,169)
mbL<-     c(166,166,166,166,NA, NA, NA)
mb<-data.frame(mbR,mbL)
mb<-data.frame(t(as.Date(date)),mb)
colnames(mb)<-c("Datum","R","L")
mb$Datum<-date

plot1<-ggplot(mb,aes(x=mb$Datum,y=mb$R))+
geom_point(data=mb,aes(x=mb$Datum,y=mb$R,color="R",size=2),
           group=mb$R,position="dodge")+
geom_line(data=mb,aes(y=mb$R,color="R",group=mb$R))+
geom_point(aes(y=mb$L,color="L",size=2),position="dodge")

plot1

I used group, otherwise I wouldn't have been able to draw any lines, still it doesn't do what I intended.

I hope you guys can help me out a little. :) It may be a minor fault.

joran
  • 169,992
  • 32
  • 429
  • 468
user3813445
  • 1
  • 1
  • 1
  • Of possible relevance: http://stackoverflow.com/questions/9617629/connecting-across-missing-values-with-geom-line – PatrickT Dec 28 '14 at 11:12

1 Answers1

4

First, melt your data to long format and then plot it. The column called variable in the melted data is the category (R or L). The column called value stores the data values for each instance of R and L. We group and color the data by variable in the call to ggplot, which gives us separate lines/points for R and L.

Also, you only need to provide the data frame and column mappings in the initial call to ggplot. They will carry through to geom_point and geom_line. Furthermore, when you provide the column names, you don't need to (and shouldn't) include the name of the data frame, because you've already specified the data frame in the data argument to ggplot.

library(reshape2)
mb.l = melt(mb, id.var="Datum")

ggplot(data=mb.l, aes(x=Datum, y=value, group=variable, color=variable)) +
  geom_point(size=2) +
  geom_line() 

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285