ggplot中轴/变量标签的键值映射

mat*_*fee 6 r ggplot2

我经常使用具有"R友好"/"程序员友好"列名的数据框,通常没有空格和/或缩写(懒惰以在进行分析时键入全名).例如:

ir <- data.frame(
   sp=iris$Species,
   sep.len=iris$Sepal.Length,
   sep.wid=iris$Sepal.Width,
   pet.len=iris$Petal.Length,
   pet.wid=iris$Petal.Width
)
Run Code Online (Sandbox Code Playgroud)

当我用ggplot绘制这些时,我经常想用"用户友好"的列名替换标签,例如

p <- ggplot(ir, aes(x=sep.len, y=sep.wid, col=sp)) + geom_point() +
  xlab("sepal length") + ylab("sepal width") + 
  scale_color_discrete("species")
Run Code Online (Sandbox Code Playgroud)

问题:有没有办法指定标签映射进入ggplot?

lazy.labels <- c(
  sp     ='species',
  sep.len='sepal length',
  sep.wid='sepal width',
  pet.len='petal length',
  pet.wid='petal width'
)
Run Code Online (Sandbox Code Playgroud)

并做一些类似的事情

p + labs(lazy.labels)
Run Code Online (Sandbox Code Playgroud)

甚至

p + xlab(lazy.labels[..x..]) + ylab(lazy.labels[..y..])
Run Code Online (Sandbox Code Playgroud)

在哪里..x..,..y..是一些自动ggplot变量保存当前X/Y变量的名称?(然后我可以将这些注释放入一个便利函数中而不必为每个图更改它们)

当我在报告中制作许多图时,这尤其有用.我总是可以ir使用"用户友好"列重命名,但之后我必须做很多事情

ggplot(ir, aes(x=`sepal length`, y=`sepal width`, ...
Run Code Online (Sandbox Code Playgroud)

由于所有的空间,这有点麻烦.

TC *_*ang 5

我深入研究了 ggplot 对象并想出了这个:好处是你不需要提前知道映射

library(ggplot2)

ir <- data.frame(
  sp = iris$Species,
  sep.len = iris$Sepal.Length,
  sep.wid = iris$Sepal.Width,
  pet.len = iris$Petal.Length,
  pet.wid = iris$Petal.Width
)

p <- ggplot(ir, aes(x=sep.len, y=sep.wid, col=sp)) +
     geom_point() +
     scale_color_discrete("species")


## for lazy labels

lazy.labels <- c(
  sp     ='species',
  sep.len='sepal length',
  sep.wid='sepal width',
  pet.len='petal length',
  pet.wid='petal width'
)

p$labels <-lapply(p$labels,function(x){as.character(lazy.labels[x])})
Run Code Online (Sandbox Code Playgroud)

或者,使用函数:

plot_with_labels <- function(p, l) {
  p$labels <- lapply(p$labels, function(x) { as.character(l[x]) } )
  return(p)
}

plot_with_labels(p, lazy.labels)
Run Code Online (Sandbox Code Playgroud)