Ben
Ben

Reputation: 6741

as_labeller with an expression in ggplot2 and facet_wrap

There is an example provided here, but I just can't make it work. Here is my use case:

df <- as.data.frame(matrix(runif(9),8,8))
angles <- c(0.112, 2.633, 3.766, 5.687, 0.867, 7.978, 8.937, 4.652)
df$factor <- as.factor(angles)
df.m <- melt(df)
ggplot(df.m, aes(variable, value)) +
  geom_boxplot() +
  facet_wrap(~factor)

enter image description here

Now I want to display rounded angles with the degree symbol. So I tried this

new.labs <- as_labeller(paste(round(as.numeric(angles)), "degree"), label_parsed)
ggplot(df.m, aes(variable, value)) +
  geom_boxplot() +
  facet_wrap(~factor, labeller=new.labs)   

But it produces empty strings.

Upvotes: 0

Views: 941

Answers (2)

YvanR
YvanR

Reputation: 375

Not using as.labeller, but this is simpler:

df <- as.data.frame(matrix(runif(9),8,8))
angles <- c(0.112, 2.633, 3.766, 5.687, 0.867, 7.978, 8.937, 4.652)
df$factor <- as.factor(round(angles))
df.m <- melt(df)

ggplot(df.m, aes(variable, value)) +
    geom_boxplot() +
    facet_wrap(~factor, labeller = label_bquote(.(as.character(factor))*degree))

Upvotes: 1

aosmith
aosmith

Reputation: 36086

I believe as.labeller is expecting either a function or a look-up table, not a variable name.

new.labs <- as_labeller(function(string) paste(round(as.numeric(string)), "*degree"), label_parsed)

ggplot(df.m, aes(variable, value)) +
    geom_boxplot() +
    facet_wrap(~factor, labeller = new.labs) 

enter image description here

Upvotes: 1

Related Questions