更改直方图中的调色板

时间:2012-02-23 09:08:45

标签: r colors histogram ggplot2

我正在尝试更改直方图的颜色,但不知道该怎么做,这是我的代码:

qplot(user, count, data=count_group, geom="histogram", fill=group,
            xlab = "users", ylab="count", 
            main="Users")+
    opts(axis.text.x=theme_text(angle=90, hjust=0, size=7))

这是我得到的直方图,但默认颜色太亮了,

enter image description here

我想使用像this

这样的颜色

我尝试添加该行,但它没有用。

  scale_fill_brewer(palette = palette)

2 个答案:

答案 0 :(得分:11)

如果你想将Brewer Set1与那么多组一起使用,你可以这样做:

library(ggplot2)

count_group <- data.frame(user=factor(rep(1:50, 2)), 
                          count=sample(100, 100, replace=T), 
                          group=factor(rep(LETTERS[1:20], 5)))

library(RColorBrewer)
cols <- colorRampPalette(brewer.pal(9, "Set1"))
ngroups <- length(unique(count_group$group))
qplot(user, count, data=count_group, geom="histogram", fill=group,
      xlab = "users", ylab="count") +
      opts(axis.text.x=theme_text(angle=90, hjust=0, size=7)) +
      scale_fill_manual(values = cols(ngroups))

Brewer Set 1 with many groups in ggplot

<小时/> 的修改

您可以创建和使用多个colorRampPalette,例如将蓝色分配给组A到J,将红色分配给组K到T:

blues <- colorRampPalette(c('dark blue', 'light blue'))
reds <- colorRampPalette(c('pink', 'dark red'))

qplot(user, count, data=count_group, geom="histogram", fill=group,
      xlab = "users", ylab="count") +
        opts(axis.text.x=theme_text(angle=90, hjust=0, size=7)) +
        scale_fill_manual(values = c(blues(10), reds(10)))
# blues(10) and reds(10) because you want blues for the first ten
#  groups, and reds thereafter. Each of these functions are equivalent
#  to providing vectors containing ten hex colors representing a gradient
#  of blues and a gradient of reds.

ggplot with blues and reds

答案 1 :(得分:1)

jbaums答案的更新。据我所知,使用新的ggplot2(截至2014年3月),可以使用以下语法:

p <- qplot(user, count, 
  data = count_group, 
  geom = "histogram", 
  stat = "bin2d",
  fill = group,
  xlab = "users", 
  ylab = "count"
)
p <- p + theme(axis.text.x = element_text(angle = 90, hjust = 0, size = 7))
p <- p + scale_fill_manual(values = cols(ngroups))
p

评论有点长,但这不是一个完整的答案,其余的代码是由jbaums给出的,必须要感谢!