0

I would like to pass the label_format expression to ggplot but I'm getting an error

#toy df
df <- data.frame(
  x = 1:10,
  y = seq(0.1,1,by=0.1),
  label_format = "scales::percent_format(accuracy=0.1)"
)

ggplot(df,aes(x=x,y=y))+
  geom_point()+
  scale_y_continuous(label=!! rlang::parse_expr( label_format))

Error in parse_exprs(x) : object 'label_format' not found

I would like to evaluate the string to end up with this plot with formatted y-axis:

ggplot(df,aes(x=x,y=y))+
  geom_point()+
  scale_y_continuous(label=scales::percent_format(accuracy = 0.1))

enter image description here

Eric
  • 1,381
  • 9
  • 24

1 Answers1

4

The scales don't have access to the global data to evaluate expressions stored in columns of the data. You can use unparsed expressions as follows though:

library(ggplot2)

df <- data.frame(
  x = 1:10,
  y = seq(0.1,1,by=0.1)
)

label_format <- "scales::percent_format(accuracy=0.1)"

ggplot(df,aes(x=x,y=y))+
  geom_point()+
  scale_y_continuous(label= eval(parse(text = label_format)))

Created on 2022-01-13 by the reprex package (v2.0.1)

teunbrand
  • 33,645
  • 4
  • 37
  • 63