Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using following code to produce a bar chart of HairEyeColor dataset:

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~.)

I get following barchart:

enter image description here

I want to color each bar in 2 colors: upper half to show hair color and lower half to show eye color, as shown in a manually created bar for black hair & brown eye color below:

enter image description here

Also, the legend needs to be removed. How can I achieve this?

HairEyeColor dataset:

> 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
205 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're going to have to define some colors because there is no "Blond" or "Hazel" color in 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...