编程指定颜色scale_fill_manual ggplot通话(Programmatically

2019-06-23 21:00发布

我要的颜色取决于特定的列中给出的值GGPLOT2小情节的背景。 使用答案我已经问前面的问题,我能拼凑我需要什么在一起。 @ joran的回答此 ,因为它示出创建一个单独的数据帧传递到ggplot的技术问题是特别有用的。

这一切都工作得很好就够了,给下面的图片中显示的输出:

下面是我用来产生上述情节的代码:

# User-defined variables go here

list_of_names <- c('aa','bb','cc','dd','ee','ff')
list_of_regions <- c('europe','north america','europe','asia','asia','japan')

# Libraries

require(ggplot2)
require(reshape)

# Create random data with meaningless column names
set.seed(123)
myrows <- 30
mydf <- data.frame(date = seq(as.Date('2012-01-01'), by = "day", length.out = myrows),
                   aa = runif(myrows, min=1, max=2),
                   bb = runif(myrows, min=1, max=2),
                   cc = runif(myrows, min=1, max=2),
                   dd = runif(myrows, min=1, max=2),
                   ee = runif(myrows, min=1, max=2),
                   ff = runif(myrows, min=1, max=2))

# Transform data frame from wide to long

mydf <- melt(mydf, id = c('date'))
mydf$region <- as.character("unassigned")

# Assign regional label

for (ii in seq_along(mydf$date)) {
    for (jj in seq_along(list_of_names)) {
        if(as.character(mydf[ii,2]) == list_of_names[jj]) {mydf$region[ii] <- as.character(list_of_regions[jj])}
    }
}

# Create data frame to pass to ggplot for facet colours
mysubset <- unique(mydf[,c('variable','region')])
mysubset$value <- median(mydf$value) # a dummy value but one within the range used in the data frame
mysubset$date <- as.Date(mydf$date[1]) # a dummy date within the range used

# ... And plot
p1 <- ggplot(mydf, aes(y = value, x = date, group = variable)) +
    geom_rect(data = mysubset, aes(fill = region), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.3) +
    scale_fill_manual(values = c("japan" = "red", "north america" = "green", "asia" = "orange", "europe" = "blue")) +
    geom_line() +
    facet_wrap( ~ variable, ncol = 2)

print (p1)

这对我的工作的现实世界的脚本旨在用于包含许多不同的数据系列的许多不同的团体,因此该脚本将被复制很多次,只有变量变更。

这使得重要的是要有用户定义的元素进行编辑显然访问,这就是为什么list_of_nameslist_of_regions变量在文件开始被摆正。 (当然,这将是最好不要需要更改脚本都而是定义这些列表作为外部文件或将其传递给脚本作为参数。)我试着用这两个概括出解决方案for循环来分配区域。 我做了反复折腾了试图让使用更R-中心的解决方案一会儿apply功能,但无法得到它的工作,所以我放弃了,坚持什么,我知道。

然而,在我的代码,因为它代表了scale_fill_manual调用需要明确传递变量来定义填充颜色,如'europe' = 'blue' 。 这些变量会根据我处理的数据有所不同,所以,在目前形式的脚本,我需要为每一组数据系列的手动编辑脚本的ggplot一部分。 我知道这将是耗时的,我强烈怀疑这也将是非常容易出错。

问:我非常希望能够以编程方式提取并定义所需的值scale_fill_manual从值之前声明的列表调用(在这种情况下,从list_of_regions )匹配的颜色先前声明的名单,但我想不出的方式来实现这一目标。 你有什么想法?

Answer 1:

这是否帮助?

cols <- rainbow(nrow(mtcars))
mtcars$car <- rownames(mtcars)

ggplot(mtcars, aes(mpg, disp, colour = car)) + geom_point() +
  scale_colour_manual(limits = mtcars$car, values = cols) +
  guides(colour = guide_legend(ncol = 3))



文章来源: Programmatically specifying colours in scale_fill_manual ggplot call
标签: r ggplot2