【问题标题】:automagically using labels (haven semantics) in ggplot2 plots在 ggplot2 图中自动使用标签(避风港语义)
【发布时间】:2018-01-25 13:57:57
【问题描述】:

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

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

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_continuous 语句?例如。就像是 scale_x_continuous(label_from_attr, breaks = breaks_from_attr, labels = value_labels_from_attr)。或者甚至可以用+ add_labels_from_attributes() 替换整个东西?

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

【问题讨论】:

  • 看看Hmisc 包,它有很多用于 ggplot 的“使用标签绘图”功能。我不确定避风港的兼容性,但我认为它使用与属性规范相同的标签。

标签: r ggplot2 r-haven


【解决方案1】:

我没有很好的规模,但你可以使用这样的功能:

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)
  )
}

然后使用 as(+ 不行):

p <- ggplot(mtcars, aes(mpg, cyl)) + geom_point()
label_x(p)

或者,使用管道:

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


旧解决方案

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)

或者对于 y 轴:

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

【讨论】:

  • 谢谢。重复数据框和变量名正是我想要避免的。但是感谢您发现ggplot_build 杀死了我们需要的属性。我也没有找到有关如何编写新音阶的信息。
  • 用不同的解决方案更新。
  • 这真的很酷!所以ggplot_build毕竟并没有杀死属性,但是我们无法通过+获得它们?
  • 它在data 中剥离了它们,但似乎在plot$data 中没有。 + 问题是因为 + 实际上并没有使绘图到目前为止可用于右侧的函数。
【解决方案2】:

另一种方法是为具有自己的类的 ggplot() 编写一个包装器。然后在调用相应的打印方法时,属性具有完全的可见性。请参阅包 'yamlet' (0.2.1) 中的 ?ag.print

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多