I am looking for ways to increase data vis efficiency for a large dataset. I have created several functions using ggplot2 to that end. Some of the resulting figures may be for distribution, consequently, I'd like them to have comprehendible titles and axis labels. I'm thinking I can associate readable labels to each variable using attr(). This way I do not have to rename the variables and deal with long variable names including spaces. I have succeeded in this when using ggplot's functions
library(ggplot2)
library(magrittr)
# Set attributes
mt <- mtcars
attr(mt$mpg, "desc") <- "Miles per Gallon"
attr(mt$cyl, "desc") <- "Number of Cylinders"
mt %>%
ggplot() +
geom_point(aes(x = cyl, y = mpg)) +
labs(x = attr(mt$cyl, "desc"),
y = attr(mt$mpg, "desc"))
The above code behaves as I expect and returns a graph containing axis labels. However, when I create a graphing function I can not figure out how to access the variable attributes. Both of the following attempts succeed in creating the graph, however do not produce the axis labels
vis_1 <- function(.data, .x, .y) {
.data %>%
ggplot() +
geom_point(aes(x = {{.x}}, y = {{.y}})) +
labs(x = attr({{.data$.x}}, "desc"),
y = attr({{.data$.y}}, "desc"))
}
vis_1(.data = mt, .x = cyl, .y = mpg)
and
vis_2 <- function(.data, .x, .y) {
attr_x <- attr(.data$.x, "desc")
attr_y <- attr(.data$.y, "desc")
.data %>%
ggplot() +
geom_point(aes(x = {{.x}}, y = {{.y}})) +
labs(x = attr_x,
y = attr_y)
}
vis_2(.data = mt, .x = cyl, .y = mpg)
Any suggestions would be appreciated.