简体   繁体   中英

How to jitter lines in ggplot2

Say I have the following data and plot:

require(reshape2)
require(ggplot2)
data <- data.frame(id=seq(1,9,1), var1=c(10,3,5,7,8,9,4,6,5), var2=c(9,3,5,7,8,9,4,6,5))
data_graph <- melt(data, id="id")
ggplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() + 
geom_text(aes(label=value), size=5, hjust=-.6, vjust=1.5)

For almost the entirety of both lines, there is overlap. Is there any way to somehow jitter the lines so that they are close to each other, but don't overlap. Or to do something to know that there are two lines?

There is a function to do just this called jitter . If you just want to add jitter to the lines in the plot, the following code will do it:

ggplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
  geom_line(size=2, 
            aes(y = jitter(value, 5), x = jitter(id, 2), group=variable, col=variable)) + 
  geom_point() + 
  geom_text(aes(label=value), size=5, hjust=-.6, vjust=1.5)

The second value in the jitter function specifies how much jitter to add

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM