HairEyeColor bar chart in R

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

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:

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:

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 

回答1:

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) 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!