R中的HairEyeColor条形图

时间:2014-10-16 01:43:37

标签: r

我使用以下代码生成HairEyeColor数据集的条形图:

mm = melt(HairEyeColor)
mm$hair_eye = paste(mm$Hair, mm$Eye, sep='_')

ggplot(mm)+geom_bar(aes(x=hair_eye, y=value, fill=hair_eye), stat='identity')+facet_grid(Sex~.)

我得到了以下条形图:

enter image description here

我想用2种颜色为每个条纹着色:上半部分显示头发颜色,下半部分显示眼睛颜色,如手动创建的黑发和黑色条形图所示。棕色眼睛颜色如下:

enter image description here

此外,需要删除图例。我怎样才能做到这一点?

HairEyeColor数据集:

> HairEyeColor
, , Sex = Male

       Eye
Hair    Brown Blue Hazel Green
  Black    32   11    10     3
  Brown    53   50    25    15
  Red      10   10     7     7
  Blond     3   30     5     8

, , Sex = Female

       Eye
Hair    Brown Blue Hazel Green
  Black    36    9     5     2
  Brown    66   34    29    14
  Red      16    7     7     7
  Blond     4   64     5     8

1 个答案:

答案 0 :(得分:1)

你必须定义一些颜色,因为colors()

中没有“金色”或“淡褐色”颜色
library(reshape2)
mm = melt(HairEyeColor)
mm <- within(mm, {
  color <- tolower(Hair)
  color <- ifelse(color == 'blond', 'yellow', color)
  color1 <- tolower(Eye)
  color1 <- ifelse(color1 == 'hazel', 'gold', color1)
  value <- value / 2
  value1 <- value
})

mm <- melt(mm, id.vars = -(4:5))
cols <- c(apply(mm[1:16, c('color','color1')], 1, c))

library(ggplot2)
ggplot(data = mm, aes(x = interaction(Hair, Eye), y = value, fill = interaction(variable, interaction(Hair, Eye)))) +
  geom_bar(stat = 'identity') + facet_grid(Sex ~ .) + 
  theme(legend.position = 'none') + 
  scale_fill_manual(values = cols)

enter image description here