Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jitter geom_line()

Tags:

plot

r

ggplot2

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, jitter geom_line

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) 
like image 618
Eric Fail Avatar asked Jun 02 '12 21:06

Eric Fail


2 Answers

You can try

geom_line(position=position_jitter(w=0.02, h=0)) 

and see if that works well.

like image 94
baptiste Avatar answered Oct 04 '22 06:10

baptiste


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.

Avoid ggplot2 lines overlapping exactly using position_dodge()

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:

prevent line overlap in ggplot with position_doge

like image 26
flexponsive Avatar answered Oct 04 '22 06:10

flexponsive