Is there a way to jitter the lines in geom_line()
? I know it kinda defies the purpose of this plot, but if you have a plot with few lines and would like them all to show it could be handy. Maybe some other solution to this visibility problem.
Please see below for code,
A <- c(1,2,3,5,1) B <- c(3,4,1,2,3) id <- 1:5 df <- data.frame(id, A, B) # install.packages(reshape2) require(reshape2) # for melt dfm <- melt(df, id=c("id")) # install.packages(ggplot2) require(ggplot2) p1 <- ggplot(data = dfm, aes(x = variable, y = value, group = id, color= as.factor(id))) + geom_line() + labs(x = "id # 1 is hardly visible as it is covered by id # 5") + scale_colour_manual(values = c('red','blue', 'green', 'yellow', 'black')) p2 <- ggplot(subset(dfm, id != 5), aes(x = variable, y = value, group = id, color= as.factor(id))) + geom_line() + labs(x = "id # 5 removed, id # 1 is visible") + scale_colour_manual(values = c('red','blue', 'green', 'yellow', 'black')) # install.packages(RODBC) require(gridExtra) grid.arrange(p1, p2)
You can try
geom_line(position=position_jitter(w=0.02, h=0))
and see if that works well.
If you just want to prevent two lines from overlapping exactly, there is now a better way: position_dodge(), which "adjusts position by dodging overlaps to the side". This is nicer than adding jitter to any line, even when it's not needed.
Code example:
df<-data.frame(x=1:10,y=1:10,z=1:10); df.m <- melt(df, id.vars = "x"); ggplot(df.m, aes(x=x,y=value,group=variable,colour=variable)) + geom_line(position=position_dodge(width=0.2));
Thanks to position_dodge()
, we can now see that there are two lines in the plot, which just happen to co-incide exactly:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With