在 R 中用户定义函数调用的绘图标题中使用列名称

问题描述 投票:0回答:2

我正在使用用户定义的函数来绘制多个变量来调用绘图,并映射以迭代多个变量。我想使用列名称的一部分为每个图添加标题。使用 str_extract 可以获取所需的文本,但我在从绘图函数中传递此文本时遇到困难

#plot with hard-coded title - this part works
require(dplyr)
require(ggplot)
require(stringr)
require(purrr)

mydf <- data.frame("category" = as.factor(sample(c("type1", "type2"), 10, replace = TRUE)),
                   "test1_results" = runif(10, min = 0, max = 100),
                   "test2_results" = runif(10, min = 50, max = 150))

make_plot <- function(data, var)  {
    data %>% 
    ggplot() +
    aes(x = .data$category, y = !!as.symbol(var), color = .data$category) +
    ggtitle("plot title") +
    geom_boxplot(width = 0.2, notch = FALSE, position = position_dodge(1), lwd = 1.8, outlier.shape = NA)
}

vars <- c("test1_results", "test2_results")
plots <- map(vars, ~make_plot(mydf, .x))
plots[[1]]

提取所需的字符串原则上是有效的 - 这会根据需要生成“test1”:

text <- "test1_results"
str_extract(text, ".*(?=_results)")

问题来了

make_plot2 <- function(data, var)  {
  title <- str_extract(!!as.symbol(var), ".*(?=_results)") # problem here
  data %>% 
    ggplot() +
    aes(x = .data$category, y = !!as.symbol(var), color = .data$category) +
    ggtitle(title) +
    geom_boxplot(width = 0.2, notch = FALSE, position = position_dodge(1), lwd = 1.8, outlier.shape = NA)
}
title <- str_extract(!!as.symbol(var), ".*(?=_results)")
vars <- c("test1_results", "test2_results")
plots2 <- map(vars, ~make_plot(mydf, .x))
plots2[[1]]

R 报告“as.vector(x, "symbol") 中出现错误: 无法将“闭包”类型强制转换为“符号”类型的向量“

我尝试了很多变体,但不确定从绘图函数环境中将列名称作为字符串传递的正确语法

r ggplot2 plot title
2个回答
0
投票

您可以直接在

str_extract
中添加
ggtitle()
:

make_plot <- function(data, var)  {
  data %>% 
    ggplot() +
    aes(x = .data$category, y = !!as.symbol(var), color = .data$category) +
    ggtitle(str_extract(var, "[^_]+")) +
    geom_boxplot(width = 0.2, notch = FALSE, position = position_dodge(1), lwd = 1.8, outlier.shape = NA)
}

vars <- c("test1_results", "test2_results")
plots <- purrr::map(vars, ~make_plot(mydf, .x))
plots[[1]]


0
投票

无需将

var
变成符号。可以直接传过去,解析出标题:

make_plot <- function(data, var)  {
  title <- str_remove(var, "_results") 
  data %>% 
    ggplot() +
    aes(x = .data$category, y = .data[[var]], color = .data$category) +
    ggtitle(title) +
    geom_boxplot(width = 0.2, notch = FALSE, position = position_dodge(1), lwd = 1.8, outlier.shape = NA)
}
vars <- c("test1_results", "test2_results")
plots <- map(vars, ~make_plot(mydf, .x))
© www.soinside.com 2019 - 2024. All rights reserved.