首页 > 解决方案 > 基于原始 CSV 文件名称的绘图名称

问题描述

我有一些 csv 文件,我需要从每个文件中生成相同的图。我已将 R 中的 csv 文件作为数据帧读取,并将它们放在一个列表中,列表中的每个元素都以原始文件命名。

问题

如何根据每个 csv 文件的名称为图命名?我对 ggplot 和 regex 函数都很陌生。

这是我尝试过的;首先,我创建了一些玩具数据框来“模仿”原始数据并将它们放在一个列表中:

library(tidyverse)

# Create four dataframes

df1_09 <- data.frame(
  first_column = c(1, 2, 3, 4),
  second_column = c(5, 6, 7, 8)
)

df1_10 <- data.frame(
  first_column = c(4, 2, 3, 1),
  second_column = c(8, 6, 7, 5)
)

df2_09 <- data.frame(
  first_column = c(9, 10, 11, 12),
  second_column = c(13, 14, 15, 16)
)

df2_10 <- data.frame(
  first_column = c(12, 10, 11, 9),
  second_column = c(16, 14, 15, 13)
)

list_of_df <- list(df1_09, df1_10, df2_09, df2_10)

现在我创建了用于绘制数据框的函数。我想将数据框的名称作为主标题。所以我试过:

# Create plot function

plot_data <- function(data) {
  ggplot(data) +
    geom_point(aes(x = data[, 1], y = data[, 2])) +
    xlim(0, 12) +
    ylim(5, 16) +
    ggtitle(paste(names(data))) +
    xlab("x axis") +
    ylab("y axis") +
    theme_bw()
}

myplots <- list()
myplots <- lapply(list_of_df, plot_data)

代码有效,但是如果我检查列表的结构,我会得到最奇怪的输出(我只是在下面粘贴了一小部分输出)

str(myplots)
#> List of 4
#>  $ df1_09:List of 9
#>   ..$ data       :'data.frame':  4 obs. of  2 variables:
#>   .. ..$ first_column : num [1:4] 1 2 3 4
#>   .. ..$ second_column: num [1:4] 5 6 7 8
#>   ..$ layers     :List of 1
#>   .. ..$ :Classes 'LayerInstance', 'Layer', 'ggproto', 'gg' <ggproto object: Class LayerInstance, Layer, gg>
#>     aes_params: list
#>     compute_aesthetics: function
#>     compute_geom_1: function
#>     compute_geom_2: function
#>     compute_position: function
#>     compute_statistic: function
#>     data: waiver
#>     draw_geom: function
#>     finish_statistics: function

此外,如果我检查第一个图,我可以看到它选择了列名,而不是数据框的名称:

myplots[[1]]

reprex 包于 2021-04-19 创建(v0.3.0)

标签: rdataframeggplot2

解决方案


library(tibble)

# Create list and keep object names as name
L <- tibble::lst(df1_09, df1_10, df2_09, df2_10)

myplots <- lapply( 1:length(L), function(i) {
  ggplot(L[[i]]) +
    geom_point(aes(x = first_column, y = second_column)) +
    xlim(0, 12) +
    ylim(5, 16) +
    ggtitle(names(L)[i]) +
    xlab("x axis") +
    ylab("y axis") +
    theme_bw()
})

myplots[[1]]

在此处输入图像描述


推荐阅读