Joe
Joe

Reputation: 3806

How to modify axis labels within ggplot labs()

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?

Upvotes: 2

Views: 694

Answers (1)

r2evans
r2evans

Reputation: 161085

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

Upvotes: 2

Related Questions