Fernando Finotto Fernando Finotto - 3 months ago 23
R Question

Insert percentage of values in ggplot

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:

http://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.

Answer

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