使用ggplot2时出现奇怪的线条

3

我有以下数据集:

> str(dat)
'data.frame':   5000 obs. of  3 variables:
 $ y: num  0.864 0.869 0.871 0.879 0.874 0.871 0.871 0.873 0.864 0.869 ...
 $ A: Factor w/ 5 levels "0.2","0.5","0.8",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ x: num  1 2 3 4 5 6 7 8 9 10 ...
> head(dat)
      y   A x
1 0.864 0.2 1
2 0.869 0.2 2
3 0.871 0.2 3
4 0.879 0.2 4
5 0.874 0.2 5
6 0.871 0.2 6

"x" 列是向量 c(1:5000)

> all(dat$x==1:5000)
[1] TRUE

因此,当绘制以下图表时,我不理解某些线条的存在:
ggplot() + geom_line(aes(x=x, y=y, color=A), data=dat) 

我要翻译的内容如下:

我所指的线在图中由三个黑箭头表示: ggplot

编辑:下面是一个类似的例子,使用可复制的模拟数据集:

set.seed(666)
mu <- rep(c(200, 400, 600, 300, 500), each=1000)
A <- factor(rep(c(1,2,3,1,2), each=1000))
y <- rnorm(length(mu), mu, 100)
dat <- data.frame(x=1:length(mu), y=y, A=A)
ggplot() + geom_line(aes(x=x, y=y, color=A), data=dat)

您能否对数据进行子集操作并生成可重现的示例?某些 yx 值可能不符合您的预期。 - Roman Luštrik
我该如何附加我的数据?我不明白这些行的原因与y值有什么关系,而且根据all(dat$x==1:5000)的结果,我确切地知道x=1:5000。 - Stéphane Laurent
好的 - 我找到了如何模拟类似的例子,我将编辑我的帖子。 - Stéphane Laurent
提供一个可重现的示例,加一分。 - Roman Luštrik
1个回答

5

您的数据框需要另一个变量来表示不同的块(即具有相同颜色的区域),并在geom_line中使用group参数:

dat <- data.frame(x=1:length(mu), y=y, A=A, B=gl(5, 1000))
ggplot() + geom_line(aes(x=x, y=y, color=A, group=B), data=dat)

ggplot output


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接