【问题标题】:bar chart of row freq ggplot2行频率ggplot2的条形图
【发布时间】:2018-12-20 00:00:35
【问题描述】:

我有以下数据:

dataf <- read.table(text = "index,group,taxa1,taxa2,taxa3,total
                s1,g1,2,5,3,10
                s2,g1,3,4,3,10
                s3,g2,1,2,7,10
                s4,g2,0,4,6,10", header = T, sep = ",")

我正在尝试制作数据频率的堆积条形图,以便它对每个索引 (s1,s2,s3,s4) 和每个组 ( g1,g2) 的每个分类群。我只能弄清楚如何绘制一个分类群的物种,但不是所有三个都堆叠在一起。

以下是我正在尝试制作的一些示例:

这些是在谷歌表格上制作的,所以它们看起来不像 ggplot,但使用 ggplot2 在 r 中制作会更容易,因为真实数据集更大。

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    您需要重塑数据。

    这是我的解决方案(按情节细分)

    第一个情节

    library(tidyverse)
    ##For first plot
    prepare_data_1 <- dataf %>% select(index, taxa1:taxa3) %>%
      gather(taxa,value, -index) %>%
      mutate(index = str_trim(index)) %>%
      group_by(index) %>% mutate(prop = value/sum(value))
    
    
    ##Plot 1
    prepare_data_1 %>%
      ggplot(aes(x = index, y = prop, fill = fct_rev(taxa))) + geom_col()
    

    第二个情节

    ##For second plot
    prepare_data_2 <- dataf %>% select(group, taxa1:taxa3) %>%
      gather(taxa,value, -group) %>%
      mutate(group = str_trim(group)) %>%
      group_by(group) %>% mutate(prop = value/sum(value))
    
    ##Plot 2
    prepare_data_2 %>%
      ggplot(aes(x = group, y = prop, fill = fct_rev(taxa))) + geom_col()
    

    【讨论】:

      【解决方案2】:
      ##You need to reshape data before doing that.    
       dfm = melt(dataf, id.vars=c("index","group"), 
                  measure.vars=c("taxa1","taxa2","taxa3"),
                  variable.name="variable", value.name="values")
      
       ggplot(dfm, aes(x = index, y = values, group = variable)) + 
              geom_col(aes(fill=variable)) +
              theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.25)) +
              geom_text(aes(label = values), position = position_stack(vjust = .5), size = 3) + theme_gray()
      

      【讨论】:

        猜你喜欢
        • 2011-02-02
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-09
        • 2014-04-13
        • 1970-01-01
        相关资源
        最近更新 更多