首页 > 解决方案 > 如何将文本粘贴到 R 中 ggplot2 图中的数字 y 轴刻度上?

问题描述

例如,使用任意数据,如果您运行以下命令,您会注意到 y 轴刻度是 2、4、6 和 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) 

如何使 y 轴刻度改为显示 2x、4x、6x 和 8x?

标签: rggplot2

解决方案


我们可以传入一个函数scale_y_continouswith pasteorstr_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')))

推荐阅读