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 が Web サイト 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 に答える