提取列数据来自的列名

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

我正在创建制作 ggplot 的函数。我需要这个函数来使用用于抽签的数据来自的列名添加一个 ggtitle。

该函数用于变量 yvar 并像这样开始:scatter_plotseries <- function(yvar). yvar is essentially a list of values from a specific column: scatter_plots <- lapply(df[, c("D_x", "D_y", "D_z", "D_j", "D_k")], scatter_plotseries) I want the name of each plot to be called D_x or D_y etc.

我在 ggplot 中尝试过的不同选项:

  • ggtitle(as.character(colnames(df$yvar)))
  • ggtitle(as.character(names(df$yvar)))
  • ggtitle(as.character(colnames(df[, yvar])))
  • ggtitle(as.character(名称(df[,yvar])))

我也尝试过这样的事情: 名称(df)[应用(df,2,函数(i)其中(i ==“D_x”))]

这些选项都没有给出特定列的名称。他们要么返回 NULL 要么返回错误。

请并感谢您的帮助!

r ggplot2 label
1个回答
0
投票

最简单的是遍历列名(例如,plot 1):

数据框是一种特殊类型的(命名)列表。在循环时访问列表名称实际上是一个经常需要的功能,例如参见 Get names of list in for loopAccess names of list elements in a loop。使用名称进行循环通常是最直接的方法,但是

purrr::imap
可以访问列表的元素和名称(例如,plot 2)。

library(ggplot2)

## Plot 1: loop over names
ls_names <- names(mtcars)
ls_p <- lapply(ls_names, function(.x) {
  ggplot(mtcars[.x], aes(x = "x", y = .data[[.x]])) +
    geom_boxplot() +
    labs(title = .x, x = NULL)
})
patchwork::wrap_plots(ls_p)


## Plot 2: use purrr::imap
ls_p_imap <- purrr::imap(mtcars, function(.x, .y) {
  ggplot() +
    geom_boxplot(aes(x = "", y = .x)) +
    labs(y = .y, title = .y, x = NULL)
})
patchwork::wrap_plots(ls_p_imap)

创建于 2023-02-22 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.