17

当您scale_fill_manual在一个因子中定义的颜色少于级别时,会ggplot2出现以下错误消息:

# Basic definition of the plot
plot <- ggplot(s4r, aes(x=DIM, y=nbexpress, fill=DIM))

# Printing plot and options
plot + geom_bar(stat="identity", show_guide=FALSE) + 
  scale_fill_manual(values=c("#CC0000", "#006600", "#669999", "#00CCCC", 
                             "#660099", "#CC0066", "#FF9999", "#FF9900")

显示:

Error: Insufficient values in manual scale. 10 needed but only 8 provided.

如何避免这个错误?这对我来说尤其重要,因为我在具有动态数据和 R 嵌入网站 CMS 的服务器上工作,并且不希望图表在出现错误级别时失败(这可能会发生,直到我们更正数据库)。

到目前为止,我已经找到了一种解决方法(请参阅我的答案),但我想知道是否有更优雅的解决方案。

4

2 回答 2

12

到目前为止,我的解决方法是为 ggplot2 提供更多颜色,如果出现更多级别,如下所示:

# Basic definition of the plot
plot <- ggplot(s4r, aes(x=DIM, y=nbexpress, fill=DIM))

# Printing plot and options + faceting if any
plot + geom_bar(stat="identity", show_guide=FALSE) + 
  scale_fill_manual(values=c("#CC0000", "#006600", "#669999", "#00CCCC", 
                             "#660099", "#CC0066", "#FF9999", "#FF9900", 
                             "black", "black", "black", "black", "black"))
于 2013-09-25T07:55:56.683 回答
4

刚刚找到了一种通过从给定池中挑选来将调色板填充到所需大小的方法。

# count the needed levels of a factor
number <- nlevels(s4r$DIM)

# repeat the given colors enough times
palette <- rep(c("color1", "color2", ...), length.out = number)

# or, if you want a random distribution:
# if you want it random, but reproducable,
# backup .Random.seed, or set your own
set.seed(23)
palette <- sample(c("color1", "color2", ...), number, replace = TRUE)

scale_fill_manual(values=palette)
于 2015-04-10T19:14:06.927 回答