How can I paste text onto numerical y-axis ticks in ggplot2 figures in R?

Viewed 142

Using arbitrary data for instance, if you run the following, you notice the y-axis ticks are 2, 4, 6, and 8:

ggplot(iris, aes(Species)) + 
  geom_line(aes(y = Sepal.Length, colour = "Sepal.Length"), size=1.25) + 
  geom_line(aes(y = Sepal.Width, colour = "Sepal.Width"), size=1.25) 

How can I make the y-axis ticks instead display 2x, 4x, 6x, and 8x?

1 Answers

We can pass a function in scale_y_continous with paste or str_c

library(ggplot2)
library(stringr)
ggplot(iris, aes(Species)) + 
  geom_line(aes(y = Sepal.Length, colour = Sepal.Length), size=1.25) + 
   geom_line(aes(y = Sepal.Width, colour = Sepal.Width), size=1.25) +    
   scale_y_continuous(labels = function(x) str_c(x, 'x'))
   # // or use as_mapper
   #  scale_y_continuous(labels = purrr::as_mapper(~ str_c(., 'x')))
Related