Quantcast
Channel: Assign name of data frame to ggplot title in purrr loop - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Assign name of data frame to ggplot title in purrr loop

$
0
0

I have two data sets from which I would like to generate histograms showing how the data overlap by name (A, B, C). I have written a custom function so I can use ggplot with map2.

I would like the graphs to be titled according to the name of each data set, so "A", "B", "C." Does anyone know of a way to do this?

# load packages library(ggplot2)library(dplyr)library(purrr)## load and format data 1df1_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 namedf1 <- lapply(df1, function(x) Map(seq.int, x$start, x$end)) # generate sequence intervalsdf1 <- map(df1, unlist) # unlist sequencesdf1 <- lapply(df1, data.frame) # convert to df## load and format data 2df2_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 namedf2 <- lapply(df2, function(x) Map(seq.int, x$start, x$end)) # generate sequence intervalsdf2 <- map(df2, unlist) # unlist sequencesdf2 <- lapply(df2, data.frame) # convert to df## write custom ggplot function and generate graphsgplot <- 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)

I also tried the following in the title field in my function:

deparse(substitute(data1))

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images