我有一个ggplot
使用分面和手动颜色分配的图表。我想在调用本身之外定义变量,这样我就不必去挖掘scale_colour_manual
和其他区域来更改使用的值breaks
或values
调用scale_colour_manual
.
假设这些是变量。
var1 <- 'series.a'
var1.label <- "Series A result"
var2 <- 'series.b'
var2.label <- "Series B result"
在values
orbreaks
我可以使用这样的东西:
c('Series A result' = alpha("blue", 0.5),'Series B result' = alpha("red",0.5))
这很好,因为上面的代码生成以下输出:
Series A result Series B result
"#0000FF80" "#FF000080"
而这段代码:
c(var1.label = alpha("blue", 0.5), var2.label = alpha("red",0.5))
不绘图是因为它产生了这个,其中元素的名称与我们用于颜色的值不匹配,即“A 系列结果”和“B 系列结果”:
var1.label var2.label
"#0000FF80" "#FF000080"
所以问题似乎是:我如何才能c()
使用变量的值而不是它们的名称?
我看过eval
,parse
甚至force
但他们似乎没有做我想做的事。我怀疑这是 R 的一个非常简单的部分,但这不是我遇到的问题。如果需要,示例代码如下。
require(ggplot2)
require(reshape)
require(scales)
# Create data
set.seed(78910)
mydf <- data.frame(
mydate = seq(as.Date('2013-01-01'),
as.Date('2013-01-10'), by = 'day'),
series.a = runif(10, 100, 200),
series.b = runif(10, 2000, 3000))
tail(mydf)
mymelt <- melt(mydf, id.var = 'mydate')
# Define user variables
var1 <- 'series.a'
var1.label <- "Series A result"
var2 <- 'series.b'
var2.label <- "Series B result"
# Which makes creating labels for the faceting easier
mymelt$label.col <- ifelse(mymelt$variable == var1, var1.label, var2.label)
tail(mymelt)
# Plots without problems
ggplot(mymelt, aes(y = value, x = mydate)) +
geom_line(aes(colour = label.col)) +
scale_colour_manual("",
breaks = c('Series A result','Series B result'),
values = c('Series A result' = alpha("blue", 0.5),
'Series B result' = alpha("red",0.5))) +
facet_wrap(~ label.col, ncol = 1, scale = "free_y")
# Does not plot
ggplot(mymelt, aes(y = value, x = mydate)) +
geom_line(aes(colour = label.col)) +
scale_colour_manual("",
breaks = c(var1.label, var2.label),
values = c(var1.label = alpha("blue", 0.5),
var2.label = alpha("red",0.5))) +
facet_wrap(~ label.col, ncol = 1, scale = "free_y")
# Not plotting because names in second case are not correct
c('Series A result' = alpha("blue", 0.5),'Series B result' = alpha("red",0.5))
c(var1.label = alpha("blue", 0.5), var2.label = alpha("red",0.5))
期望的结果是这种图像: