在ggplot2图中

时间:2018-01-25 13:57:58

标签: r ggplot2 r-haven

我正在使用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这样的帮助器来略微缩短上面的属性代码,但这不是我想要的。

2 个答案:

答案 0 :(得分:2)

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

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

enter image description here

旧解决方案

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

答案 1 :(得分:0)

另一种方法是为具有自己的类的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()

agplot of disp versus mpg