R:我如何使用变量来定义scale_colour_manual和键标签颜色?

时间:2012-02-14 19:11:05

标签: r ggplot2

我想在ggplot图表中使用变量作为图例键标签,该图表使用两个geom_line图和scale_colour_manual。如果我明确使用字符串来定义图例键标签,那么一切正常,就像6.4.4节一样。在哈德利的书中,p.109。

enter image description here

另一方面,如果我在变量中弹出标签并使用geom_line和scale_colour_manual调用中的变量,则没有任何反应。

enter image description here

正如您所看到的,情节'p1'的效果很好。 Plot'p2'没有显示两个线图,但它确实显示了正确的键标签。用于生成两个图的代码如下。 (此请求的背景是我想将图例键标签传递给包装函数。)

问。为什么下面p2中使用的方法不起作用?如何使用变量来定义键标签并将它们链接到键标签中的正确颜色?

require(ggplot2)
require(lubridate)

set.seed(12345)
# create dummy time series data
monthsback <- 60
startdate <- as.Date(paste(year(now()),month(now()),"1",sep="-")) - months(monthsback)
x <- data.frame(mydate=seq(as.Date(startdate), by="month", length.out=monthsback),
          myval1=runif(monthsback, min=600, max=800), 
          myval2=runif(monthsback, min=400, max=600))
var1 <- "foo-var"
var2 <- "bar-var"

p1 <- ggplot(x, aes( mydate, myval1)) +
    geom_line( aes( x = mydate, y = myval1, colour = "foo"), size = 0.5) +
    geom_line( aes( x = mydate, y = myval2, colour = "bar"), size = 0.5) +
    scale_colour_manual("Legend", values = c("foo" = "red", "bar" = "blue"))
print (p1)

p2 <- ggplot(x, aes( mydate, myval1)) +
    geom_line( aes( x = mydate, y = myval1, colour = var1), size = 0.5) +
    geom_line( aes( x = mydate, y = myval2, colour = var2), size = 0.5) +
    scale_colour_manual("Legend", values = c(var1 = "red", var2 = "blue"))
#print (p2)

1 个答案:

答案 0 :(得分:4)

我做了很多,因为我使用了很多“标准化”的情节选项。我确信有一种更优雅的方式来挖掘proto对象,但结果是相同的,看看str(tmp),你将更好地理解被映射的内容:

tmp <-  scale_colour_manual("Legend", values = c(var1 = "red", var2 = "blue"))
# str(tmp)
names(tmp$values) <- c(var1,var2)

p2 <- ggplot(x, aes( mydate, myval1)) +
geom_line( aes( x = mydate, y = myval1, colour = var1), size = 0.5) +
geom_line( aes( x = mydate, y = myval2, colour = var2), size = 0.5) + tmp

enter image description here

顺便说一句,你可以将ggplot + ggplot元素保存到列表中,然后以编程方式编辑列表项(有点像我上面所做的那样)。

例如:

z <- list(geom_line( aes( x = mydate, y = myval1, colour = var1), size = 0.5),
geom_line( aes( x = mydate, y = myval2, colour = var2), size = 0.5),
tmp)

ggplot(x, aes( mydate, myval1)) + z