R ggplot2错误:手动比例中的值不足

R ggplot2错误:手动比例中的值不足,r,ggplot2,R,Ggplot2,当使用scale\u fill\u 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(v

当使用
scale\u fill\u 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")
如何避免这个错误?这对我来说尤其重要,因为我在一个服务器上工作,服务器上嵌入了动态数据和CMS网站中的R,并且不希望在出现错误级别时图形失败(这可能会发生,直到我们更正了数据库)


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

到目前为止,我的解决方案是在出现更多级别时,为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"))
#绘图的基本定义

plot刚刚找到了一种方法,通过从给定的池中拾取,将调色板填充到所需的大小

# 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)
#计算系数所需的级别

如果你不知道你有哪些类别,我想知道手动定义的色阶的目的是什么。如果你只是想让每个条有不同的颜色,你可以使用
因子的
级别。但是,用户可能会犯错误,拼写错误。。。谁会添加一个不需要的级别,不在手动定义的颜色比例中,它会以一个丑陋的错误停止处理图形。我的解决方法是使用一些故障保护颜色,而不是过滤掉不需要的级别…我不是说你根本不知道你的数据是什么样子,我的意思是由于噪音和其他因素,刻度不是很有用。嗯,最好是
scale\u fill\u manual(values=c(“my.value.1”=“white”,“my.value.2”=“red”,…)
在这里定义期望的级别,并且您可以按照自己的意愿填充其余的,不是吗?@ATN您经常希望强制ggplot在不同的绘图中对每个因子始终使用相同的颜色。
# 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)