简体   繁体   English

如何在ggplot2中抖动线

[英]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 . 有一个功能可以做到这一点,即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 jitter功能中的第二个值指定要添加的抖动量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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