2

I'm quite new in R, but I'm trying to do a facet_grid using ggplot package in R and, for better data visualization, I'd like to insert the percentage of values in each quadrant for the column groupings, like the image below:

https://i.stack.imgur.com/Zt7ev.png

Can be one or another, in each quadrant or in legend.

My code is this one below

ggplot(df1_final,aes(x=revenue,y=visits,col=groupings)) +
  geom_jitter(alpha=I(1/2)) + 
  xlim(c(0,20000)) + 
  facet_grid(group_lvl_1_visits ~ group_lvl_1_revenue)

Could anyone help me on this?

EDIT: Both solutions helped me a lot, very good ones.

lmo
  • 37,904
  • 9
  • 56
  • 69
  • 1
    Welcome to Stack Overflow! [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269) – zx8754 Jul 21 '16 at 19:57
  • having a `dput(df1_final)` pasted in to your example would help folks help you. – hrbrmstr Jul 21 '16 at 20:40

2 Answers2

3

Here's one way to do it:

library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class, nrow = 4) ->
  p
p + geom_text(
  data = setNames(as.data.frame(prop.table(table(mpg$class))),c("class", "lab")),
  mapping = aes(label = scales::percent(lab)), 
  x = 4, 
  y = 40
)

enter image description here

or, for facet_grid:

p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p <- p + facet_grid(drv ~ cyl)
p + geom_text(
  data = setNames(as.data.frame(prop.table(table(mpg$drv, mpg$cyl)), stringsAsFactors = F), c("drv","cyl","lab")),
  mapping = aes(label = scales::percent(lab)),
  x=4.5, 
  y=30
)

enter image description here

lukeA
  • 53,097
  • 5
  • 97
  • 100
2

Here's a tidyverse + label-in-legend solution:

library(ggplot2)
library(dplyr)
library(scales)

group_by(mpg, cyl, drv) %>% 
  mutate(color=sprintf("%s-%s",cyl,drv)) %>% 
  ungroup(mpg) -> mpg

gg <- ggplot(mpg, aes(displ, cty))
gg <- gg + geom_point(aes(color=color))
gg <- gg + facet_grid(drv ~ cyl)

count(mpg, color) %>% 
  ungroup() %>% 
  mutate(pct=percent(n/sum(n)),
         lab=sprintf("%s (%s)", color, pct)) -> pct_df


gg <- gg + scale_color_discrete(name="Title", labels=pct_df$lab)
gg

enter image description here

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205