Search code examples
rggplot2fillgeom-bar

ggplot: Set colours with 2+ factors


I have a dataset with 2 factors, each with 2 levels. I want to make a grouped bar graph with 4 different colours.

The data looks like this:

TrialType Group yvar
TP         C     1
TP         E     2
TA         C     3
TA         E     4

I use this to make the bar graph using

ggplot(data=k, aes(x=V2, y=V3, fill=V1)) + 
  geom_bar(stat="identity", position="dodge", color="#000000") + 
  scale_fill_manual(values=c("#d7191c", "#FFBB45"), breaks=c("TA", "TP"))

And I get the this graph.

Is there a way to make this graph so the bars go Dark red/light red/dark yellow/light yellow from left to right? So that the Groups are delineated based on red/yellow, and the trial type is delineated based on darkness?

Thanks a lot!
Mrinmayi


Solution

  • Basically like this, using interaction to get a unique color for each combination:

    ggplot(data=k, aes(x=Group, y=yvar, fill=interaction(TrialType,Group))) + 
      geom_bar(stat="identity", position="dodge", color="#000000")+
      scale_fill_manual(values = c("dark red", "pink", "yellow", "light yellow"))
    

    enter image description here