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

0

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

nice! text = unique(df$label_format) works with my original df

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.