9

until now I can't find an appropriate answer, here is my short question about ggplot2 in R:

data(mtcars)
ggplot(data=mtcars, aes(x=mpg, y=wt, fill=factor(cyl))) +
scale_fill_manual(values=c("red","orange","blue"))+
geom_point(size=2, pch=21)+
facet_grid(.~cyl)

enter image description here

This is all fine, now I want all data points (regardless what number cyl has) in every facet (e.g. with a smooth grey below the points)?

Thanks, Michael

mod_che
  • 137
  • 1
  • 6
  • 4
    Possible duplicate of [plotting the whole data within each facet using facet\_wrap and ggplot2](http://stackoverflow.com/questions/35550411/plotting-the-whole-data-within-each-facet-using-facet-wrap-and-ggplot2) – erc Apr 19 '16 at 09:59

2 Answers2

12

Here is a slight simplification that makes life a bit easier. The only thing you need to do is to remove the faceting variable from the data provided to the background geom_point() layer.

library(tidyverse)
ggplot(data=mtcars, aes(x=mpg, y=wt)) + 
  geom_point(data=select(mtcars,-cyl), colour="grey") +
  geom_point(size=2, pch=21, aes(fill=factor(cyl))) + 
  scale_fill_manual(values=c("red","orange","blue")) + 
  facet_wrap(~cyl) 

atiretoo
  • 1,812
  • 19
  • 33
6

Using the link given by @beetroot, I was able to do something like this :

g1 <- ggplot(data=mtcars, aes(x=mpg, y=wt)) + 
  geom_point(data=mtcars[, c("mpg", "wt")], aes(x=mpg, y=wt), colour="grey") +
  geom_point(size=2, pch=21, aes(fill=factor(cyl))) + 
  scale_fill_manual(values=c("red","orange","blue")) + 
  facet_wrap(~cyl) 

This produces the plot : enter image description here

Hope this helps you.

Kumar Manglam
  • 2,780
  • 1
  • 19
  • 28
  • Thanks. I will elaborate the proposed link. Thanks also for your suggestion, but here I get: "Error: Aesthetics must be either length 1 or the same as the data (60): x, y, fill" when I applied it in this way to my specific data (but data structure is the same). – mod_che Apr 19 '16 at 11:19
  • @mod_che : The code that I have wrote, is this also giving you error? For me, it works fine. – Kumar Manglam Apr 19 '16 at 12:00