【发布时间】:2020-12-21 20:40:05
【问题描述】:
我有两个数据集,我想从中生成直方图,显示数据如何按名称(A、B、C)重叠。我已经编写了一个自定义函数,因此我可以将 ggplot 与 map2 一起使用。
我希望根据每个数据集的名称为图表命名,例如“A”、“B”、“C”。有谁知道这样做的方法吗?
# load packages
library(ggplot2)
library(dplyr)
library(purrr)
## load and format data 1
df1_raw <- data.frame(name = c("A", "B", "C", "A", "C", "B"),
start = c(1, 3, 4, 5, 2, 1),
end = c(6, 5, 7, 8, 6, 7))
df1 <- split(x = df1_raw, f = df1_raw$name) # split data by name
df1 <- lapply(df1, function(x) Map(seq.int, x$start, x$end)) # generate sequence intervals
df1 <- map(df1, unlist) # unlist sequences
df1 <- lapply(df1, data.frame) # convert to df
## load and format data 2
df2_raw <- data.frame(name = c("C", "B", "C", "A", "A", "B"),
start = c(5, 4, 3, 4, 4, 5),
end = c(7, 8, 7, 6, 9, 6))
df2 <- split(x = df2_raw, f = df2_raw$name) # split data by name
df2 <- lapply(df2, function(x) Map(seq.int, x$start, x$end)) # generate sequence intervals
df2 <- map(df2, unlist) # unlist sequences
df2 <- lapply(df2, data.frame) # convert to df
## write custom ggplot function and generate graphs
gplot <- function(data1, data2) {
ggplot() +
geom_histogram(data = data1, aes(x = X..i..), binwidth = 1, color = "grey", fill = "grey") +
geom_histogram(data = data2, aes(x = X..i..), binwidth = 1, fill = "pink", alpha = 0.7) +
labs(
title = ls(data1))
}
hist <- map2(df1, df2, gplot)
我还在函数的标题字段中尝试了以下内容:
deparse(substitute(data1))
【问题讨论】:
-
仅供参考 - 您需要反引号(在
1键旁边),而不是单引号,用于代码格式化 -
谢谢,我使用了错误的字符,我很困惑为什么它不起作用。
-
deparse(substitute(data1))是执行此操作的正常方法,但是将其放在purrr循环中会使事情变得更加困难。您最好的选择可能是编辑您的函数以采用title参数并将names(df1)添加到您正在循环的参数列表中。