【问题标题】:ggplot2 Error: Insufficient values in manual scaleggplot2 错误:手动刻度中的值不足
【发布时间】:2013-09-30 17:05:56
【问题描述】:

当您使用 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 中,并且不希望图表在出现错误级别时失败(这可能会发生,直到我们更正数据库)。

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

【问题讨论】:

  • 如果您不知道自己拥有哪些类别,我想知道手动定义色标的目的是什么。如果您只想为每个条形使用不同的颜色,您也许可以使用factorlevels
  • 实际上,在我的用例中,我确实知道我拥有哪些类别。但随后,可能会出现用户错误、拼写错误……谁会添加一个不存在于手动定义的颜色比例中的不需要的级别,从而停止处理带有 ugly 错误的图形。我的解决方法是设置一些故障安全颜色,而不是过滤掉不需要的级别......
  • 我不是说你根本不知道你的数据是什么样子的,我是说由于噪音和其他因素,规模不是很有用。恕我直言,最好是scale_fill_manual(values=c("my.value.1"="white", "my.value.2"="red", ...)),您可以在其中定义预期水平,您可以根据需要填写其余部分,您不觉得吗?
  • @ATN 很多时候,您希望强制 ggplot 对不同绘图中的每个因素始终使用相同的颜色。

标签: r ggplot2


【解决方案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)

【讨论】:

    【解决方案2】:

    到目前为止,我的解决方法是为 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"))
    

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2014-07-06
      • 2019-01-04
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多