Colouring points by factor within the margin of a faceted ggplot2 plot in R

后端 未结 2 1014
难免孤独
难免孤独 2020-12-31 17:26

I\'d like to create a faceted plot with margins in ggplot2. However, I\'d like the margin plot to have colours according to from which facet the particular point has been de

相关标签:
2条回答
  • 2020-12-31 17:45

    Another option would be to create the faceted plots and margin plot separately and use the gridExtra library to combine them:

    library(ggplot2)
    library(gridExtra)
    mtcars$ALL <- "all"
    p <- ggplot(mtcars, aes(mpg, wt))
    p1 <- p + geom_point() + facet_grid(.~gear)
    p2 <- p + geom_point(aes(color=factor(gear))) + facet_grid(.~ALL)
    grid.arrange(p1, p2, ncol=2)
    

    enter image description here

    0 讨论(0)
  • 2020-12-31 18:04

    How about creating a new variable as a reference and colour the points by that? Seems to work provided you don't mind the points in the first 3 facets being coloured too.

    mtcars$ref <- as.factor(mtcars$gear)
    
    p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(col=as.factor(gear)))
    p + facet_grid(.~ref, margins = TRUE)
    

    All points coloured by gear

    EDIT: I have managed to get it to remove the colour key from the first 3 facets but not without playing around with the original data;

    Duplicate the original data (so there are 2 of each record) then instead of using a margin plot to produce the "all" facet, using the redundant records instead.

    library(ggplot2)
    
    mtcars$ref <- (mtcars$gear)
    
    # create the duplicate
    dat <- do.call("rbind", replicate(2, mtcars, simplify = FALSE)) 
    
    # give the duplicates a false value for "gear" so they can be plotted together 
    #This value can then be used for faceting, grouping everything with "all".
    
    dat$ref[1:32] <- "all" 
    
    
    # where not in the "all" facet, change "gear" to one (so they are plotted with the same colour)
    dat$gear[dat$ref != "all"] <- 1
    
    # then plot using ref as the facet and gear to colour points.
    
    p <- ggplot(dat, aes(mpg, wt)) + geom_point(aes(col=as.factor(gear)))
    p + facet_grid(.~ref, margins = F)
    

    Points only coloured by gear in final facet

    I'm not sure that's the best way to go about it but perhaps someone with more expertise might be able to advise?

    0 讨论(0)
提交回复
热议问题