Andy.Jian Andy.Jian - 11 days ago 5
R Question

How can I get stack plot for data.frame in the nested list?

I got data.frame in the nested list after I split them by given threshold. However, I am going to generate stack bar plot to make data more informative and easy to understand. I think using ggplot2 packages could be good choice, but I am quite new for using this packages, doing this is not intuitive.How can I get stack bar plot for data.frame in the nested list ? Any way getting bar plot, or pie graph for data.frame object easily ? Any idea ?

mini data :

myList <- list(
hola= data.frame( from=seq(1, by=4, len=15), to=seq(3, by=4, len=15), value=sample(30, 15)),
boo = data.frame( from=seq(3, by=7, len=20), to=seq(6, by=7, len=20), value=sample(45, 20)),
meh = data.frame( from=seq(4, by=8, len=25), to=seq(7, by=8, len=25), value=sample(36, 25))
)


helper function :

splitter <- function(mlist, threshold) {
res <- lapply(mlist, function(x) {
splt <- split(x, ifelse(x$value >= threshold, "pass", "fail"))
})
return(res)
}

#' @example
splitMe <- splitter(myList, threshold = 10)


I want to generate stack bar plot, pie graph by using ggplot2 packages. How can I make this happen easily ? Can any one point me how to do this task ?

my desired output could be something like this : enter image description here

How can I get stack bar plot for data.frame in the nested list ? How can I achieve my desired output plot ? Thanks a lot

Answer

You may not get these chart directly with this. But i think you will get the idea. Key is you need to get your data in proper format in order to plot.

Here i do some data manipulation for getting the data into data frame.

df=as.data.frame(unlist(lapply(splitMe,function(x) unlist(x))))
df$col=row.names(df)
names(df)[1]='val';row.names(df)=NULL

You can make making the new columns more dynamic.

df$col=gsub(paste("\\.|*[0-9]",lapply(splitMe[[1]], function(x) paste(names(x), collapse = "|"))[1], collapse = "", sep = "|"),"",df$col)
df$col1=gsub(paste(lapply(splitMe, function(x) paste(names(x), collapse = "|"))[1], collapse = "", sep = "|"),"",df$col)
df$col2=gsub(paste(names(splitMe), collapse = "|"),"",df$col)

Now i get the data in format which ggplot can easily work with.

library(ggplot2)
ggplot(data = df, aes(x = col1,  fill = col2)) + geom_bar()

And you will get a plot like this. Bar plot