r - 基于原始 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)
解决方案
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]]
推荐阅读
- vue.js - 类更改属性的转换
- ssrs-2012 - SSRS 工具提示未显示
- azure-ad-b2c - Microsoft.Identity.Client 返回格式错误的结果
- python - 在内存中存储一个大的稀疏矩阵来计算特征值
- .htaccess - 删除内容位置响应标头
- vuejs2 - VueJS - 嵌套 v-on:click 和 v-if 使组件消失
- scala - 使用 GroupBy Pivot Agg 在 Scala Spark 中重塑 DataFrame
- logging - Vertx 日志记录:访问请求上下文
- android - 如何使用 JNI 从 Android 本机 C++ 调用 PackageManager.hasSystemFeature?
- visual-studio-code - VS 代码调试器停止