Why doesn't the ggplot2 legend combine manual fill and scale?

Expected Behavior

If I created a graph using ggplot2 and used separate, say, form and fill scales to separate the data, I would expect the legend to draw a distinction between โ€œwhiteโ€ filled dots (which look empty) and โ€œblackโ€ filled dots (which do not look hollow).

In the code example below, the legend element for Windows should be a white hollow dot, and for Linux - a dot filled with black

Actual behavior

The legend elements in the Operating System section display two visually identical points for clearly different operating systems, the points of which are clearly indicated by different fills on the graph. In the code example below, both the legend and Windows and Linux are represented as indistinguishable black hollow dots in the legend, even if they are correctly plotted differently on the graph.

Plot sample

Sample plot with broken fill behavior in the legend

Code example

library(ggplot2) x <- rnorm(n = 30) y <- rnorm(n = 30) treatment <- rep(c("red", "green", "blue"), times = 20) operatingSystem <- rep(c("Windows", "Linux"), times = 30) dd <- data.frame(x, y, treatment, operatingSystem) fillScaleValues <- c( "Windows" = "white", "Linux" = "black" ) shapeScaleValues <- c( "red" = 21, "green" = 22, "blue" = 23 ) p <- ggplot( aes(x = x, y = y, shape = factor(treatment), fill = factor(operatingSystem) ), data = dd ) p <- p + geom_point() p <- p + scale_fill_manual(values = fillScaleValues, name = "Operating System") p <- p + scale_shape_manual(values = shapeScaleValues, name = "Treatment") p 

Session Information

 R version 2.15.1 (2012-06-22) Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) locale: [1] C/en_US.UTF-8/C/C/C/C attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] ggplot2_0.9.2.1 reshape2_1.2.1 plyr_1.7.1 ProjectTemplate_0.4-2 [5] testthat_0.7 loaded via a namespace (and not attached): [1] MASS_7.3-21 RColorBrewer_1.0-5 colorspace_1.1-1 dichromat_1.2-4 [5] digest_0.5.2 evaluate_0.4.2 grid_2.15.1 gtable_0.1.1 [9] labeling_0.1 memoise_0.1 munsell_0.4 proto_0.3-9.2 [13] scales_0.2.2 stringr_0.6.1 tools_2.15.1 
+12
r ggplot2
Sep 19 '12 at 5:08
source share
1 answer

You must redefine the form that is used in the legend, as shown in this question .

So, using your sample code (thanks for the clear, reproducible question, by the way), you only need:

 p + guides(fill = guide_legend(override.aes = list(shape = 21))) 

What gives you what you wanted:

Proper legend

+14
Sep 19 '12 at 6:30
source share



All Articles