Tuesday, November 24, 2015

R: MIssing legend when using scale_fill_manual

When configuring ggplot using scale_fill_manual in R, sometimes the legend might not be displayed. This happens when we specify 'breaks' property within the scale_fill_manual command, and the values we supply don't correspond to the factor levels we use in fill.

For instance, assume we have a data frame with columns 'X', 'Y', and 'Type', where 'Type' contains values 'A' and 'B'. In the below ggplot/ggplot2 command, breaks argument cannot contain a list of strings which do not map to factor levels in column 'Type':
ggplot2(data=df, aes(x=X, y=Y, fill=Type)) + 
scale_fill_manual(values=c("black","red", name="Type", breaks=c("A","B"), labels=c("Type-A","Type-B"))

Instead, we need to specify the breaks as:
ggplot2(data=df, aes(x=X, y=Y, fill=Type)) + 
scale_fill_manual(values=c("black","red", name="Type", breaks=levels(factor(df$Type)), labels=c("Type-A","Type-B"))

Or as below, if we are sure of the factor ordering:
ggplot2(data=df, aes(x=X, y=Y, fill=Type)) + 
scale_fill_manual(values=c("black","red", name="Type", labels=c("Type-A","Type-B"))

References:
1. http://stackoverflow.com/questions/14546858/missing-legend-when-combining-scale-fill-manual-and-scale-x-discrete-in-bar-char

1 comment:

  1. Great and useful comment. I just had this issue. Thanks!

    ReplyDelete