Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

r - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...