我经常使用具有“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
)
当我使用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`, ...
由于所有的空格,这有点繁琐。
x.var <- 'sep.len'
有关,让 ggplot 正确解释变量名为sep.len
而不是x.var
(aes_string
可以解决这个问题)。 - mathematical.coffeelabs()
函数暗示“标签”是一个合适的词选择,但是该函数可能不是大多数用户介绍这种图形组件的方式。当使用scale_*()
时,相关参数是name
,而labels
参数则选择断点的标签。当使用theme()
时,相关参数是axis.title.*
。我认为最好使用theme()
中的术语,因为它具有一组唯一的参数,对应于一个几乎耗尽的图形组件集合。 - randy