我经常使用带有“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/