更改ggplot2中变量和类别的颜色 [英] Changing the colour of both variables and categories in ggplot2
问题描述
我想创建一个堆叠的条形图,其中不仅变量具有唯一的颜色,而且类别也具有
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.
只是为了清除它,最终图应具有8种不同的颜色:每对类别/变量将具有手动分配的不同颜色.
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
推荐答案
好吧,在这种情况下,您只需为每个唯一的组合创建一个变量(在这种情况下,每行一个,但是将两个变量粘贴在一起会有点麻烦一般;您也可以使用 interaction
):
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"))
这篇关于更改ggplot2中变量和类别的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!