2

Say I want to modify a ggplot axis label with the str_to_title() function.

library(tidyverse) mtcars %>% ggplot(aes(x = wt, y = mpg)) + geom_point() + labs(x = ~str_to_title(.x)) 

Rather than my x-axis being labeled 'Wt' it will be labeled 'str_to_title(.x)'. Is there a way to apply functions within the labs() function?

1 Answer 1

2

labs doesn't do programmatic NSE like many other components of ggplot2. One option is to define the columns programmatically, use aes_ and as.name (or other ways too) and it'll work.

library(ggplot2) library(stringr) # str_to_title xx <- "wt"; yy <- "mpg" ggplot(mtcars, aes_(x = as.name(xx), y = as.name(yy))) + geom_point() + labs(x = str_to_title(xx)) 

ggplot with "dynamic" x-label

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.