首页 > 解决方案 > 如何绘制具有数据框的分组 geom_bar 图?

问题描述

我有一个像这样的数据框:

在此处输入图像描述

并想在 R 中绘制如下内容:

在此处输入图像描述

但由于某种原因,我真的在为分组的 geom_bar 代码苦苦挣扎......你能帮帮我吗?

标签: rggplot2tidyverse

解决方案


我们可以barplot使用base R

barplot(t(df1), beside = TRUE, col = c("blue", "orange", "grey", 
       "yellow", "lightblue" ))

-输出

在此处输入图像描述


或者如果我们需要一个ggplot/plotly

library(ggplot2)
library(dplyr)
library(tidyr)
library(plotly)
library(tibble)
p <- df1 %>% 
   rownames_to_column('rn') %>%
   pivot_longer(cols = -rn) %>%
   ggplot(aes(x = rn, y = value, fill = name)) +
        geom_col(position = 'dodge') + 
     theme_bw()
ggplotly(p)

-输出

在此处输入图像描述

数据

df1 <- structure(list(A = c(65, 9, 7, 70, 9), B = c(23, 4, 5, 53, 2), 
    C = c(42, 5, 2, 17, 7), D = c(51, 7, 5, 57, 5), E = c(14, 
    2, 2, 13, 4)), class = "data.frame", row.names = c("AAA", 
"BBB", "CCC", "DDD", "EEE"))

推荐阅读