ggplot2 / colorbrewer定性调色板,有125个类别

时间:2013-02-08 15:22:44

标签: r ggplot2 colorbrewer

我的数据如下:

  • 10州
  • 每个州都有两种类型
  • 每种类型都有1到29个实体
  • 每个州实体类型都有一个计数

完整数据available as a gist

我正在尝试想象每个实体的计数比例。为此,我使用了以下代码:

icc <- transform( icc, state=factor(state), entity=factor(entity), type=factor(type) )
p <- ggplot( icc, aes( x=state, y=count, fill=entity ) ) +
  geom_bar( stat="identity", position="stack" ) +
  facet_grid( type ~ . )
custom_theme <- theme_update(legend.position="none")
p

plot

不幸的是,我丢失了很多信息,因为有很多实体的状态类型没有显示足够的独特颜色。

如上所述,我有125个实体,但是状态类型中的大多数实体是29.有没有办法强制ggplot2和colorbrewer在每个实体类型中分配一个唯一的(并且希望相当不同)颜色?

到目前为止,我提出的唯一方法是将entity强制转换为整数,该整数有效,但不会在各级之间提供太多的色差。

1 个答案:

答案 0 :(得分:6)

这是一种为您提供更多信息的方法。取rainbow生成的色轮,对于其他每种颜色,将其与方向盘上的相反颜色交换。

col <- rainbow(30)
col.index <- ifelse(seq(col) %% 2, 
                    seq(col), 
                    (seq(ceiling(length(col)/2), length.out=length(col)) %% length(col)) + 1)
mixed <- col[col.index]

p <- ggplot(icc, aes(x=state, y=count, fill=entity)) +
  geom_bar(stat="identity", position="stack") +
  facet_grid( type ~ . ) + 
  scale_fill_manual(values=rep(mixed, length.out=nrow(icc)))

custom_theme <- theme_update(legend.position='none')
p

enter image description here