如何置换data.frame列表并在ggplot2中创建带注释的堆栈条形图?

时间:2016-11-27 11:03:03

标签: r dataframe ggplot2 annotations

我有data.frame列表,需要先进行置换,并为每个data.frame创建带注释的堆栈条形图。我在SO中搜索过相关帖子并了解了如何做到这一点。但是,我按照我的预期拍摄了如何制作它,但是如果data.frame相当大,我的代码很慢,而不需要获得堆栈条形图。所以我不断阅读ggplot2的插图以获得解决方案。我坚持以期望的方式置换data.frame列表。如何置换data.frame列表并创建带注释的堆栈条图?任何人都可以让我知道如何轻松有效地做到这一点?如何操作data.frame列表并获得带注释的堆积条形图(观察数量,标签)?提前致谢

可重复的data.frame:

confirmedDF <- list(
  bar = data.frame(begin=seq(2, by=11, len=25), end=seq(8, by=11, len=25), score=sample(54,25)),
  cat = data.frame(begin=seq(5, by=8, len=35), end=seq(9, by=8, len=35), score=sample(45,35)),
  foo = data.frame(begin=seq(8, by=13, len=25), end=seq(17, by=13, len=25), score=sample(49,25))
)

discardedDF <- list(
  bar = data.frame(begin=seq(3, by=12, len=40), end=seq(8, by=12, len=40), score=sample(72,40)),
  cat = data.frame(begin=seq(9, by=15, len=50), end=seq(17, by=15, len=50), score=sample(60,50)),
  foo = data.frame(begin=seq(21, by=19, len=30), end=seq(32, by=19, len=30), score=sample(42,30))
)

然后是我的data.frame输入列表:

library(tidyverse)
library(magrittr)

names(confirmedDF) <- paste("confirmed", names(confirmedDF), sep = ".")
names(discardedDF) <- paste("discarded", names(discardedDF), sep = ".")
merged <- do.call(rbind, c(confirmedDF, discardedDF))
merged %<>% rownames_to_column(var = "cn")
merged %<>% separate(cn, c("list", "letters", "seq"), sep = "\\.")
merged %<>% mutate(stringency = ifelse(score >= 12, "Stringent", "Weak"))

res <- merged %>% split(list(.$letters, .$stringency, .$list))

我尝试获取每个单独的堆栈条形图,琐碎的代码如下:

library(dplyr)
library(ggplot2)

lapply(res, function(ele_) {
  plot_data <- ele_ %>%
    group_by(sample, stringency, list) %>%
    tally %>%
    group_by(sample, stringency) %>%
    mutate(percentage = n / sum(n), cumsum = cumsum(percentage))

  ggplot(data = plot_data, aes(x = sample,  y= n ,fill = stringency)) + 
    geom_bar(position = "dodge",stat = "identity")
})

我不明白使用lapply来获得每个条形图是非常缓慢和低效的。以上琐碎的代码没有给出我想要的条形图。我该如何优化代码?如何置换data.frame列表并获取带注释的条形图?

如何实现我想要的输出堆栈条形图?有什么想法吗?

1 个答案:

答案 0 :(得分:3)

你可以试试这个:

res %>% 
  bind_rows %>% 
  group_by(stringency, list, sample) %>% 
  tally %>% 
  ungroup %>% 
  setNames(c("var", "val", "sample", "n")) %>% 
  {bind_rows(., setNames(., c("val", "var", "sample", "n")))} %>% 
  ggplot(aes(x=var, y=n, fill=val)) + 
  geom_col() + 
  geom_text(aes(label=n), position=position_stack(vjust = 0.5)) + 
  facet_wrap(~sample) 

enter image description here