Changing the colour of both variables and categories in ggplot2

安稳与你 提交于 2021-01-28 05:36:39

问题


I would like to create a stacked bar plot in which not only the variable has its only color but also the category

a = c("A","A","B","B","C","C","D","D")
b = c("inclusion","exclusion","inclusion","exclusion","inclusion","exclusion","inclusion","exclusion")
c = c(60,20,20,80,50,55,25,20)
dat = data.frame(category=a, variable=b, value=c)
dat

category  variable value
1        A inclusion    60
2        A exclusion    20
3        B inclusion    20
4        B exclusion    80
5        C inclusion    50
6        C exclusion    55
7        D inclusion    25
8        D exclusion    20

A plot with costum variable colors can be created easily enough:

colors <- c("#9ECAE1","#F03B20")
ggplot(dat, aes(category, value, fill = variable)) +
geom_bar()+
scale_fill_manual(values = colors)

The question is how to manually change also the colors of the categories? Any help would be appreciated.

EDIT: just to clear it up the final plot should have 8 different colours: each pair category/variable would have a different colour manually assigned.

http://i.stack.imgur.com/G9uKt.png


回答1:


Ok, in that case, you just create a variable for each unique combination (in this case one per row, but pasting the two variables together is a bit more general; you could also use interaction):

dat$grp <- paste(dat$category,dat$variable)

ggplot(dat, aes(category, value, fill = grp)) +
    geom_bar()+
    scale_fill_manual(values = brewer.pal(8,"Reds"))


来源:https://stackoverflow.com/questions/9739266/changing-the-colour-of-both-variables-and-categories-in-ggplot2

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