如何在R中的ggplot2图形中将文本粘贴到数值型y轴刻度上?

3

例如使用任意数据,如果你运行以下命令,会发现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?
1个回答

3
我们可以在 scale_y_continuous 中使用 pastestr_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')))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接