[英]How can I get stack bar plot for list of data.frame where keeping or removing duplicated rows?
[英]How can I get stack plot for data.frame in the nested list?
按給定閾值拆分后,我在嵌套列表中得到了data.frame。 但是,我將生成堆棧條形圖,以使數據更具信息性和易於理解。 我認為使用ggplot2軟件包可能是個不錯的選擇,但對於使用此軟件包我還是一個新手,這樣做不是很直觀。如何在嵌套列表中獲取data.frame的堆棧圖? 任何方式都可以輕松獲取條形圖或data.frame對象的餅圖嗎? 任何想法 ?
迷你數據:
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))
)
輔助功能:
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)
我想通過使用ggplot2包生成堆棧條形圖,餅圖。 我如何才能輕松做到這一點? 有人能指點我如何完成這項任務嗎?
如何在嵌套列表中獲取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
您可以使新列更加動態。
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)
現在我得到了ggplot可以輕松使用的格式的數據。
library(ggplot2)
ggplot(data = df, aes(x = col1, fill = col2)) + geom_bar()
I get inspiration form Chirayu Chamoli' solution :
plot_data <- df %>%
group_by(col1, col, col2) %>%
tally %>%
group_by(col, col2) %>%
mutate(percentage = n/sum(n), cumsum = cumsum(percentage))
library(ggplot2)
ggplot(data = plot_data, aes(x = col1, y=n ,fill = col2, width = .85)) +
geom_bar(stat = "identity")+
geom_text(aes(label=n), position = position_stack(vjust = .5))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.