当您使用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中,并且当有一些错误的级别时不希望图形失败(这可能发生,直到我们更正了数据库)。
到目前为止,我找到了一种解决方法(请参阅我的回答),但我想知道是否有更优雅的解决方案。
答案 0 :(得分:6)
到目前为止我的解决方法是为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"))
答案 1 :(得分:1)
刚刚找到了一种方法,可以通过从给定的池中挑选来将调色板填充到所需的大小。
# 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)