【问题标题】:Stacked bar plot with ggplot2ggplot2的堆积条形图
【发布时间】:2021-10-16 20:25:18
【问题描述】:

我有一个这种形式的 R 数据框:(第一,第二,...是行名;A,B,...是列名)

              A   B   C    D  E
 first        30  0   0    0  0
 second       0   20  120  0  0
 third        0   40  100  0  0
 fourth       0   0   0    30 60

我想要 ggplot() 做的是绘制一个条形图,其中 x 轴上的行名称和 y 轴上的行总和,这些行总和应该按列标题类别进行颜色堆叠,并带有数字标签,所以对于上面的数据是这样的:

【问题讨论】:

  • 你是什么意思'颜色堆叠'?

标签: r ggplot2 plot bar-chart


【解决方案1】:

您应该在数据框中添加行名作为变量,并将数据转换为长格式,以便 ggplot 可以处理它。这样的事情接近你的意思我的想法:

yourDataFrame %>% 
    mutate(Label = rownames(df)) %>% # add row names as a variable
    reshape2::melt(.) %>% # melt to long format
    ggplot(., aes(x = Label, y = value, fill = variable)) + 
        geom_bar(stat='identity')

【讨论】:

    【解决方案2】:

    我认为您正在寻找这样的东西:

    df %>%
      rownames_to_column(var = 'x') %>%
      pivot_longer(-x) %>%
      filter(value > 0) %>% 
      mutate(x = factor(x, levels = c('first', 'second', 'third', 'forth'))) %>% 
      ggplot(aes(fill = forcats::fct_rev(name), y = value, x = x, label = value)) +
      geom_bar(position="stack", stat="identity") +
      geom_text(aes(label=value)) +
      theme(legend.title = element_blank())
    

    数据:

    structure(list(A = c(30L, 0L, 0L, 0L), B = c(0L, 20L, 40L, 0L
    ), C = c(0L, 120L, 100L, 0L), D = c(0L, 0L, 0L, 30L), E = c(0L, 
    0L, 0L, 60L)), class = "data.frame", row.names = c("first", "second", 
    "third", "forth")) -> df
    

    【讨论】: