0

I know how to show all facets of subcategories of a dataset, but how can I show only one facet/subgroup along with the total? (Example taken from r-cookbook.com)

library(reshape2) # for the tips data
library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
sp + facet_grid(. ~ sex)

returns the following image:

Two facets

Now I want the left (right) facet to display the entire dataset and the other facet shall stay as it is.

MERose
  • 4,048
  • 7
  • 53
  • 79

1 Answers1

3

You need to do this:

library(reshape2) # for the tips data
library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
sp + facet_grid(. ~ sex, margins=T) #margins=True will add the total 

NOTE

Using facet_grid there is no way to isolate only some of the facets along with the total. To do this check the update.

UPDATE

In order to replicate what you would like to do with the facets you would need the gridExtra library and do the following:

library(reshape2) # for the tips data
library(ggplot2)
library(gridExtra)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) + ggtitle('All') 
sh <- ggplot(subset(tips,sex=='Male'), aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) + ggtitle('Men') +
        theme(axis.title.y=element_blank(), axis.ticks.y=element_blank(), axis.text.y=element_blank())

grid.arrange(sp,sh,nrow=1,ncol=2)

with gridExtra

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • Thanks for the `margins=TRUE` option. That's already half the solution. On the other hand: Your two facets Male and (all) are identical. (all) does not include the Female dots. Also, there are good reasons to avoid `subset()`, set [this SO question](http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset). – MERose Nov 18 '14 at 17:29
  • Yeah you were right. This is the only way to achieve what you need but it involves another library. Hope it helps. I think this is the only way. Check the update. – LyzandeR Nov 18 '14 at 19:01