【问题标题】:ggplot barplot of each row (R)每行的ggplot条形图(R)
【发布时间】:2021-02-13 23:28:32
【问题描述】:

我有一个如下所示的数据集:

    a  b  a_total b_total 
dog 3  5  10      8
cat 6  2  12      13
pig 9  3  15      9

我正在尝试使用 ggplot 制作一个堆叠的条形图,让每个动物的底部有“a_total”,顶部有“a”。我试过了,但没有用。

ggplot(df, aes(x = "", y = c("a", "a_total")) + geom_bar(stat= "identity") 

我该怎么办?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我们从行名 (rownames_to_column)、select 'a' 列以及新列中创建一列,重塑为“长”格式 (pivot_longer) 并进行绘图

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    df %>%
        rownames_to_column('animal') %>% 
        select(animal, a, a_total) %>% 
        pivot_longer(cols = -animal) %>% 
        ggplot(aes(x = animal, y = value, fill = name)) + 
            geom_bar(stat = 'identity') +
            theme_bw()
    

    -输出


    此外,facet_wrap 中的“a”和“b”都可以这样做

    df %>%
         rownames_to_column('animal') %>%
         pivot_longer(cols = -animal) %>%
         mutate(abgrp = substr(name, 1, 1)) %>% 
         ggplot(aes(x = animal, y = value, fill = name)) + 
           geom_bar(stat = 'identity') + 
           theme_bw() + 
           facet_wrap(~ abgrp)
    

    base R,我们可以使用barplot

    barplot(t(df[c('a', 'a_total')]), col = c('red', 'blue'), legend = TRUE)
    

    数据

    df <- structure(list(a = c(3L, 6L, 9L), b = c(5L, 2L, 3L), a_total = c(10L, 
    12L, 15L), b_total = c(8L, 13L, 9L)), class = "data.frame", row.names = c("dog", 
    "cat", "pig"))
    

    【讨论】:

    • 有没有办法使用 facet_wrap 改变两个图的顺序? EX)订购它 b a 而不是 a b?
    • @benefactor-anchovy32 你可以改成factordf %&gt;% rownames_to_column('animal') %&gt;% pivot_longer(cols = -animal) %&gt;% mutate(abgrp = substr(name, 1, 1), abgrp = factor(abgrp, levels = c('b', 'a'))) %&gt;% ggplot(aes(x = animal, y = value, fill = name)) + geom_bar(stat = 'identity') + theme_bw() + facet_wrap(~ abgrp)
    • @benefactor-anchovy32 和更改图例中的顺序使用guides guide_legend
    猜你喜欢
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    相关资源
    最近更新 更多