所以这是这个问题的后续问题:ggplot: aes vs aes_string, or how to programmatically specify column names?
为了我自己的目的,我根据这个问题调整了解决方案但是我遇到了传奇故障。我在这里建立了一个例子:
# Set up some example data
colnames <- c(paste0 ( "y", 1:30))
nr <- 5
m1 <- matrix(data = runif(nr * length(colnames)), nrow=nr, ncol=length(colnames))
data <- data.frame(time=1:nr, m1)
names(data) <- c("time", colnames)
# Define groups of columns
s1 <- sample(colnames, 3)
s2 <- sample(colnames[!colnames %in% s1], 3)
s3 <- sample(colnames[!colnames %in% c(s1, s2) ], 3)
s4 <- sample(colnames[!colnames %in% c(s1, s2) ], 3)
# Code to add lines to the graph by column group
add_lines1 <- lapply(s1, function(i) geom_line(aes_q(y = as.name(i)), colour = "red"))
add_lines2 <- lapply(s2, function(i) geom_line(aes_q(y = as.name(i)), colour = "blue"))
add_lines3 <- lapply(s3, function(i) geom_line(aes_q(y = as.name(i)), colour = "orange"))
add_lines4 <- lapply(s4, function(i) geom_line(aes_q(y = as.name(i)), colour = "purple"))
# Draw plots with different column groups
p1 <- ggplot(data, aes(x = time))
p1 <- p1 + add_lines1 + add_lines2
p2 <- ggplot(data, aes(x = time))
p2 <- p2 + add_lines1 + add_lines3 + add_lines4
grid.arrange( p1, p2)
正如您所看到的 - 这会生成一个包含我想要但不是图例的颜色的图表:
所以我可以修改addlines
以尝试按如下方式解决此问题(差异在as.name(i)
之后的括号中):
add_lines1 <- lapply(s1, function(i) geom_line(aes_q(y = as.name(i), colour = "red")))
add_lines2 <- lapply(s2, function(i) geom_line(aes_q(y = as.name(i), colour = "blue")))
add_lines3 <- lapply(s3, function(i) geom_line(aes_q(y = as.name(i), colour = "orange")))
add_lines4 <- lapply(s4, function(i) geom_line(aes_q(y = as.name(i), colour = "purple")))
这将给我一个带有图例的图表 - 但现在我已经失去了对颜色的控制。更糟糕的是,图表中的颜色不一致:
我的问题是如何在不失去对线条颜色的控制的情况下将颜色编码的图例添加到上图?
答案 0 :(得分:1)
将colour=
来电中的aes
来电更改为您希望在图例中显示的内容:
geom_line
然后在完整的add_lines1 <- lapply(s1, function(i) geom_line(aes_q(y = as.name(i), colour = "Line1")))
add_lines2 <- lapply(s2, function(i) geom_line(aes_q(y = as.name(i), colour = "Line2")))
add_lines3 <- lapply(s3, function(i) geom_line(aes_q(y = as.name(i), colour = "Line3")))
add_lines4 <- lapply(s4, function(i) geom_line(aes_q(y = as.name(i), colour = "Line4")))
调用中添加scale_color_manual()
以获得一致的颜色(您选择的颜色)
ggplot