R 在ggplot2绘图中自动使用标签(避风港语义)

R 在ggplot2绘图中自动使用标签(避风港语义),r,ggplot2,r-haven,R,Ggplot2,R Haven,我正在绘制使用标记的数据,即变量和值具有通过属性定义的标签 通常,这些标签也是我想要的轴标题和刻度 library(ggplot2) mtcars$mpg = haven::labelled(mtcars$mpg, labels = c("low" = 10, "high" = 30)) attributes(mtcars$mpg)$label = "miles per gallon" ggplot(mtcars, aes(mpg, cyl)) + geom_point() + scale_x

我正在绘制使用标记的数据,即变量和值具有通过属性定义的标签

通常,这些标签也是我想要的轴标题和刻度

library(ggplot2)
mtcars$mpg = haven::labelled(mtcars$mpg, labels = c("low" = 10, "high" = 30))
attributes(mtcars$mpg)$label = "miles per gallon"
ggplot(mtcars, aes(mpg, cyl)) + geom_point() + 
scale_x_continuous(attributes(mtcars$mpg)$label, 
     breaks = attributes(mtcars$mpg)$labels, 
     labels = names(attributes(mtcars$mpg)$labels))
我是否可以编写一个助手,用更容易迭代的内容替换费劲的scale_x_连续语句?比如说
scale\u x\u continuous(label\u from\u attr,breaks=breaks\u from\u attr,labels=value\u labels\u from\u attr)
。或者甚至可以从属性()添加标签来替换整个东西


我知道我可以编写/使用帮助程序,如
Hmisc::label
来稍微缩短上面的属性代码,但这不是我想要的。

我没有很好的比例,但您可以使用这样的函数:

label_x <- function(p) {
  b <- ggplot_build(p)
  x <- b$plot$data[[b$plot$labels$x]]
  
  p + scale_x_continuous(
    attributes(x)$label, 
    breaks = attributes(x)$labels, 
    labels = names(attributes(x)$labels)
  )
}
或者,使用管道:

mtcars %>% { ggplot(., aes(mpg, cyl)) + geom_point() } %>% label_x()


老办法 或对于y轴:

ggplot(mtcars, aes(cyl, mpg)) + geom_point() + use_labelled(mtcars$cyl, "y")

另一种方法是为具有自己类的ggplot()编写包装器。当调用相应的打印方法时,属性具有完全可见性。参见包装“yamlet”(0.2.1)中的ag.print

库(ggplot2)
图书馆(yamlet)
图书馆(magrittr)
mtcars$disp%%结构(标签=‘位移’,单位=‘立方英寸’)
mtcars$mpg%%结构(标签为“里程”,单位为“英里/加仑”)
mtcars$am%%系数(等级=c(0,1),标签=c(‘自动’、‘手动’)
mtcars$am%%结构(标签=‘传输’)
agplot(mtcars、aes(显示、mpg、颜色=am))+geom_点()

谢谢。重复数据帧和变量名正是我想要避免的。但是感谢您仔细研究了
ggplot\u build
杀死了我们需要的属性。我也没有找到关于如何写一个新的规模的信息。更新了一个不同的解决方案。这实际上是相当酷!因此,
ggplot\u build
毕竟不会杀死属性,但我们无法通过
+
获得它们?它在
data
中剥离属性,但在
plot$data
中似乎没有。
+
问题是因为到目前为止,
+
实际上并没有使绘图可用于右侧的函数。请看一下
Hmisc
软件包,该软件包有许多ggplot的“使用标签绘图”功能。我不确定haven的兼容性,但我认为它使用了与属性规范相同的标签。
use_labelled <- function(l, axis = "x") {
    if (axis == "x")  {
        scale_x_continuous(attributes(l)$label, 
                           breaks = attributes(l)$labels, 
                           labels = names(attributes(l)$labels))
    } 
    if (axis == "y") {
        scale_y_continuous(attributes(l)$label, 
                          breaks = attributes(l)$labels, 
                          labels = names(attributes(l)$labels))
    }
}
ggplot(mtcars, aes(mpg, cyl)) + geom_point() + use_labelled(mtcars$cyl)
ggplot(mtcars, aes(cyl, mpg)) + geom_point() + use_labelled(mtcars$cyl, "y")
library(ggplot2)
library(yamlet)
library(magrittr)

mtcars$disp %<>% structure(label = 'displacement', unit = 'cu. in.')
mtcars$mpg %<>% structure(label = 'mileage', unit = 'miles/gallon')
mtcars$am %<>% factor(levels = c(0,1), labels = c('automatic','manual'))
mtcars$am %<>% structure(label = 'transmission')

agplot(mtcars, aes(disp, mpg, color = am)) + geom_point()