我正在绘制使用港湾语义学标记的数据,即变量和值具有通过属性定义的标签。
通常,这些标签也是我想要在我的轴标题和滴答。
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这样的助手来稍微缩短上面的属性代码,但这不是我想要的。
发布于 2018-01-25 15:38:31
我没有很好的比例,但是您可以使用这样的函数:
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")发布于 2019-12-26 15:57:46
另一种方法是为有自己类的ggplot()编写一个包装器。然后,当调用相应的print方法时,属性具有完全可见性。参见包'yamlet‘中的?ag.print (0.2.1)。
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()

https://stackoverflow.com/questions/48444641
复制相似问题