【发布时间】:2022-08-15 20:46:00
【问题描述】:
概括:
当设置aes(group = ID) 时,GGplot 似乎按字母顺序绘制线图。
每个 ID 的线是根据其(字母)顺序绘制的。在我的情况下,这导致了一个非常繁忙的情节。我想要一个特定的行团体在后台。更具体地说,我希望背景中的那些行在其组中具有最多的值,这样它们就不会与只有少数值的组中的行重叠。
问题:
如何以首先绘制具有最多值的组的方式重新排序数据?
代码:
首先是一些生成数据的代码(不漂亮,但结果很好):
rm(list=ls())
set.seed(42)
library(\'ggplot2\')
numOfValues <- c(20, 6, 3, 2)
System <- c(letters[1:4])
times <- c(1,2,3)
slope <- sample(1:4, size = 4)
df <- data.frame()
row <- 1
for (sys in 1:length(System)) {
for (num in 1:numOfValues[sys]) {
for (t in 1:length(times)) {
# this seems stupid, but to be consistent with my data I need unique but
# ordered ID\'s
df[row, \'ID\'] <- paste(\'P\',
num + if (System[sys] == \'a\') {0}
else if (System[sys] == \'b\') {20}
else if (System[sys] == \'c\') {26}
else if (System[sys] == \'d\') {28} ,
sep=\'_\')
df[row, \'System\'] <- System[sys]
df[row, \'Time\'] <- paste(\'T\', times[t], sep = \'\')
df[row, \'Value\'] <- runif(1, 1, 10) + times[t] + slope[sys]
row <- row + 1
}
}
}
p <- ggplot(data = df,
aes(x = Time,
y = Value,
group = ID,
colour = System,
label = ID)) +
geom_line(size = 1.5) +
geom_point(size = 3,
aes(shape = System)) +
theme_bw()
p
这是我用 ggplot 绘制的代码
p <- ggplot(data = df,
aes(x = Time,
y = Value,
group = ID,
colour = System,
label = ID)) +
geom_line(size = 1.5) +
geom_point(size = 3,
aes(shape = System)) +
theme_bw()
p
这导致了这个图表:
您可以看到组中的一些红线一个a 在顶部,有些则更多位于紫色/绿色线后面的背景中。 似乎线条是按顺序绘制的团体来自ggplot的美学,在这种情况下是由ID.这里提到了这一点:
How can I define line plotting order in ggplot2 for grouped lines?。
正如那里所建议的那样,我可以在单独的 geom_line 调用中绘制每个组,但我认为必须有其他方式。上面提到的问题中发布的第二个解决方案让我思考,但我无法将它应用到我的代码中,因为我需要按我的列“系统”对(样本)ID 进行分组。
我想如果我像我的组一样以正确的顺序重构我的 ID 列,我可以告诉 ggplot 首先绘制与内部值最多的组相对应的那些行。
我还能尝试告诉 ggplot 绘制线条而不是ID但是通过系统? 如何根据他们的组订购已分解的 ID?