2

我使用 RColorBrewer 在 ggplot2 中设置颜色。我写了一个函数,并在同一张图表上叠加了 1 到 4 行。为了设置我使用的颜色:

scale_color_brewer(type="qual", palette="Set1")

根据手册“对于定性调色板,可用的不同值的最低数量始终为 3”,因此当行数等于 1 或 2 时,我会收到警告消息。有什么 claver 技巧可以应付吗?

罗伯特

@Ben Bolker:您绝对正确,在许多情况下必须提交一个可重现的示例,尽管这里没有必要。因为我的原始函数很长,所以我准备了简单的例子来说明问题。

library("datasets")
library("ggplot2")

set.seed(1367)
y <- log10(lynx)
y.estim <- y + rnorm(length(y), sd=0.2)
mydf <- data.frame(time=1:length(y), y, y.estim) 
mydf <- melt(mydf, id="time")

p <- ggplot(mydf, aes(x=time, y=value, color=variable))
p + geom_line() + geom_point(size=2) + theme_bw() +
   scale_color_brewer(type="qual", palette="Set1") #here is a problem

也许我可以直接指定颜色。我知道

library("RColorBrewer")
> brewer.pal(4, "Set1")
[1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3"

是否可以使用例如“#E41A1C”?

4

1 回答 1

3

正如@mnel 建议的那样,将语句包装在显式print语句中似乎可行:

suppressWarnings(print(p + geom_line() + geom_point(size=2) + theme_bw() +
     scale_color_brewer(type="qual", palette="Set1")))

会话信息:

> sessionInfo()
R Under development (unstable) (2012-10-14 r60940)
Platform: i686-pc-linux-gnu (32-bit)

[snip]

other attached packages:
[1] reshape2_1.2.1  ggplot2_0.9.2.1

编辑 - @mnel

您可以重新定义print.ggplot以自动执行此操作。我不知道这是否会导致环境(parent.frame问题)

print.ggplot <- function(..., warnings = getOption('ggplot_warning', default = TRUE)){
  if(warnings){
    ggplot2:::print.ggplot(...))} else { 
     suppressWarnings(ggplot2:::print.ggplot(...))
   }
  }

因此,如果您想将 ggplot 打印的所有警告设置为关闭,您只需设置

options(ggplot_warning = FALSE)

否则它应该正常运行。

于 2012-11-01T12:31:14.163 回答