Using different scales as fill by coefficient

cnt = 100 df <- data.frame(x = c(rnorm(cnt, mean = 3), rnorm(cnt, mean = 0)), y = rnorm(2 * cnt), g = rep(0:1, each = cnt)) ggplot(df, aes(x, y, color = as.factor(g))) + stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") 

This creates a filled outline graph based on a factor: enter image description here

I would like to use different fill scales for each path, so g = 0 has a red fill and g = 1 has a blue fill. Is this possible, and if so, how?

+7
source share
1 answer

As @joran already noted, the main design in ggplot is one scale on aes . Therefore, operating conditions of varying degrees of deformity are required. Often they include the creation of one or more plot objects, the manipulation of various components of the object, and then the creation of a new plot from the object (s) managed.

Here, two plot objects with different fill color palettes β€” one red and one blue β€” are created by setting the colors to scale_fill_continuous . In a β€œred” story object, the red fill colors in the lines belonging to one of the groups are replaced with blue colors from the corresponding lines in the β€œblue” story object.

 library(ggplot2) library(grid) library(gtable) # plot with red fill p1 <- ggplot(data = df, aes(x, y, color = as.factor(g))) + stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") + scale_fill_continuous(low = "grey", high = "red", space = "Lab", name = "g = 0") + scale_colour_discrete(guide = FALSE) + theme_classic() # plot with blue fill p2 <- ggplot(data = df, aes(x, y, color = as.factor(g))) + stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") + scale_fill_continuous(low = "grey", high = "blue", space = "Lab", name = "g = 1") + scale_colour_discrete(guide = FALSE) + theme_classic() # grab plot data pp1 <- ggplot_build(p1) pp2 <- ggplot_build(p2)$data[[1]] # replace red fill colours in pp1 with blue colours from pp2 when group is 2 pp1$data[[1]]$fill[grep(pattern = "^2", pp2$group)] <- pp2$fill[grep(pattern = "^2", pp2$group)] # build plot grobs grob1 <- ggplot_gtable(pp1) grob2 <- ggplotGrob(p2) # build legend grobs leg1 <- gtable_filter(grob1, "guide-box") leg2 <- gtable_filter(grob2, "guide-box") leg <- gtable:::rbind_gtable(leg1[["grobs"]][[1]], leg2[["grobs"]][[1]], "first") # replace legend in 'red' plot grob1$grobs[grob1$layout$name == "guide-box"][[1]] <- leg # plot grid.newpage() grid.draw(grob1) 

enter image description here

+6
source

All Articles