Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201943

How to combine line and points plots with ggplot2 in R

$
0
0

I would like to use ggplot2 to plot 3 time series in the same graph. I'd like to plot the first 2 series as solid lines without points. And I would like to plot the third series with points only and no line. How can I do that?

library(ggplot2)
library(reshape2)

d1=c(1,2,3,2,1,2,3,4,5,6,5,4,3,1)
d2=c(0,2,4,5,4,3,2,4,6,7,6,5,3,1)
d3=c(0,1,2,4,4,2,1,3,4,7,8,3,5,0)

ts1 = ts(d1,c(2015,01),c(2016,03),frequency=12) 
ts2 = ts(d2,c(2015,01),c(2016,03),frequency=12) 
ts3 = ts(d3,c(2015,01),c(2016,03),frequency=12) 

#prepare data for ggplot
dat = ts.union(ts1,ts2,ts3)
dat = melt(dat,id.vars="x")

#add dates
dates=seq(as.Date("2015-01-01"), as.Date("2016-03-01"), by="months")
dat$Date = dates

p=ggplot(dat,aes(x=Date, y=value,col=Var2))+ 
  geom_line(aes(linetype=Var2), size=1) +
  geom_point(aes(shape=Var2), size=2) +
  scale_linetype_manual(values = c(1,1,1)) +
  scale_shape_manual(values=c(0,1,2))
print(p)

Viewing all articles
Browse latest Browse all 201943

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>