ggplot中的轴/变量标签的键-值映射 [英] Key-value mapping of axis/variable labels in ggplot

查看:80
本文介绍了ggplot中的轴/变量标签的键-值映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用具有"R友好"/程序员友好"列名的数据框,通常不带空格和/或缩写(在分析时不愿输入全名).例如:

I often work with dataframes with "R-friendly"/"programmer-friendly" column names, typically with no spaces, and/or abbreviated (lazy to type the full names when doing the analysis). For example:

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绘制这些标签时,我经常想用用户友好"列名称替换标签,例如

When I plot these with ggplot I often want to replace the labels with "user-friendly" column names, e.g.

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的标签映射?

Question: Is there some way to specify label mappings to pass into 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变量的名称? (然后,我可以将这些注释放入便捷函数中,而不必为每个图形都进行更改)

where ..x.., ..y.. is some automagic ggplot variable holding the name of the current X/Y variable? (then I can put these annotations into a convenience function without having to change them for each graph)

当我在报告中绘制许多图时,这特别有用.我总是可以使用用户友好"列来重命名ir,但是随后我必须做很多

This is particularly useful when I make many plots in reports. I can always rename ir with the "user-friendly" columns, but then I have to do a lot of

ggplot(ir, aes(x=`sepal length`, y=`sepal width`, ...

由于所有空格,这有点麻烦.

which is a bit cumbersome because of all the spaces.

推荐答案

我研究了ggplot对象,并提出了这一点:好处是您不需要预先知道映射

I digged into the ggplot object and came up with this: the benefit is that you do not need to know the mapping in advance

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)

这篇关于ggplot中的轴/变量标签的键-值映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆