jessexknight
jessexknight

Reputation: 825

split / process ".data" by groups

I want to add group-wise labels using geom_text based on the magical .data object. However, because .data is a "pronoun", I cant split it or even identify it's names. What is the best way to split .data by group (i.e. here: facet * colour = 6 total groups) so that I can add a unique label per-group?

The MWE below is simplified a lot from my actual code; I need to use .data so please don't suggest to mutate X before the ggplot.

library('ggplot2')

set.seed(0)
n = 900
X = data.frame(i=1:n,a=1:3,b=4:5)
X$y = runif(n,X$a,X$b)

fun = function(.df){
  rep(1:6,n/6)
}

g = ggplot(X,aes(y=y,colour=factor(b))) +
  geom_text(aes(y=0,x=0,label=fun(.data)),check_overlap=TRUE) +
  facet_grid('~a') +
  geom_boxplot()
print(g)

Upvotes: -1

Views: 65

Answers (1)

stefan
stefan

Reputation: 124148

Not clear to me why you need the .data pronoun. As you want a unique id per combo of the variable mapped on color and the facetting variable you can do so using the interaction of these variables:

library("ggplot2")

set.seed(0)
n <- 900
X <- data.frame(i = 1:n, a = 1:3, b = 4:5)
X$y <- runif(n, X$a, X$b)

ggplot(X, aes(y = y, colour = factor(b))) +
  geom_text(
    aes(y = 0, x = 0, label = as.numeric(interaction(a, b))),
    check_overlap = TRUE,
    position = position_dodge(.75)
  ) +
  facet_grid("~a") +
  geom_boxplot()

Upvotes: 1

Related Questions