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

标签 r ggplot2

我经常使用带有“R-friendly”/“programmer-friendly”列名称的数据框,通常没有空格和/或缩写(在进行分析时懒得输入全名)。例如:

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
)

当我用 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")

问题:有什么方法可以指定标签映射传递给 ggplot 吗?
lazy.labels <- c(
  sp     ='species',
  sep.len='sepal length',
  sep.wid='sepal width',
  pet.len='petal length',
  pet.wid='petal width'
)

并做类似的事情
p + labs(lazy.labels)

甚至
p + xlab(lazy.labels[..x..]) + ylab(lazy.labels[..y..])

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

当我在报告中制作许多绘图时,这特别有用。我可以随时重命名 ir使用“用户友好”列,但随后我必须做很多
ggplot(ir, aes(x=`sepal length`, y=`sepal width`, ...

由于所有空间,这有点麻烦。

最佳答案

我深入研究了 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])})

或者,使用函数:
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)

关于r - ggplot中轴/变量标签的键值映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238042/

相关文章:

r - R中匹配函数的奇怪行为

r - 相当于已弃用的 select_() 和 mutate_()

r - ggplot 轴标签中的数学(集合)符号

r - 使用 ggplot 与使用基本 R 函数时的图形结果不同?

r - 在 R (CRAN) 中创建和裁剪网格

r - HTS 包 : how to specify a network-like hierarchy of forecasts?

r - 努力在 R 中创建数据透视表

r - R:ggplot更好的渐变色

r - 限制geom_line的x轴范围(由斜率和截距定义)

r - ggplot 线图 : is there a way to depict the data points under or over the line plot depending on what looks better?