Coloring points along the edge of the boundary plot of ggplot2 in R

I would like to create a faceted plot with margins in ggplot2. However, I would like the margin chart to have colors according to which the facet was defined. This is probably best illustrated by an example:

library(ggplot2) p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p + facet_grid(.~gear, margins = TRUE) 

Within the box labeled β€œ(all),” I want those points that have β€œgear = 3” to be drawn in the same color, those that have β€œgear = 4” with a second color, and those that have "transfer" = 5 "with the third.

This does not work:

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

Is there any way to achieve what I want?

+8
r ggplot2 facets
source share
2 answers

How to create a new variable as a reference and color its points? It seems to work if you don't mind the dots in the first three faces being colored.

 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 colored by gear

EDIT: I managed to get him to remove the color key from the first three faces, but not without the source data;

Duplicate the source data (therefore, there are two records for each record), and instead use the field graph to create an β€œall” facet, using backup 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 colored by gear in final facet

I'm not sure the best way to do this, but maybe someone with more experience can advise?

+3
source share

Another option would be to create graphs and fields separately and use the gridExtra library to gridExtra 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

+1
source share

All Articles