Search code examples
rggplot2fill

adding additional fill variable in ggplot2


I have the following data and code:

#data
Congruency <- c("C", "C", "C", "C", "C", "C", "NC", "NC", "NC", "NC", "NC", "NC")
Event <- c("contact", "description", "dislocation", "manipulation", "oration", "perception", "contact", "description", "dislocation", "manipulation", "oration", "perception")
Speech_VP <- c("N", "N", "N", "N", "CH", "N", "N", "N", "N", "N", "CH", "N")
n <- c(5, 486, 97, 44, 228, 12, 23, 232, 34, 73, 130, 26)

#create dataframe
plot_df <- data.frame(Congruency, Event, Speech_VP, n)

#plot
library(ggplot2)
ggplot(data=plot_df, aes(x=Event, y=n, fill=Congruency, group = Speech_VP)) +
  geom_bar(stat="identity", position = "stack") +labs(y= "Count", x = "Event Type") + guides(fill=guide_legend(title="Congruence"))

Which produces the following plot:

plot sample

I cannot figure out how to integrate additional fill, in this case, the 'Speech_VP' column in the data frame. I looked into the ggpattern package as per questions like this one, but the syntax is difficult and it doesn't quite fit my use case.

For this particular dataset, only the 'oration' column has the Speech_VP values of "CH". Is there some way I could make this column have slashes through it or a cross-hatch, and have a legend that shows that the effect is for CH, and the solid color is for N?


Solution

  • You could facet on Speech_VP, specifying "free" for scales and space:

    ggplot(data=plot_df, aes(x=Event, y=n, 
           fill=Congruency, group = Speech_VP)) +
      geom_bar(stat="identity", position = "stack") +
      labs(y= "Count", x = "Event Type") + 
      guides(fill=guide_legend(title="Congruence")) +
      facet_grid(~Speech_VP, 
                  scales="free_x", space ="free", labeller=label_both) +
      theme_minimal()
    

    enter image description here