首页 > 解决方案 > R中的反向分组条形图

问题描述

我有 35 位参与者的数据,例如其中第一列是种族,其余三列是代谢物值

,其中第一列是种族,其余三列是三种代谢物的值,我需要一个条形图代谢物值的条形图

对于按种族分组的每种代谢物。我尝试了不同的方法,但都没有成功。如果您能帮助我,我将不胜感激。

谢谢

标签: rggplot2bar-chart

解决方案


这将按酶和伦理对虚拟数据组进行汇总并获得“值”列的平均值,然后绘制图。在 geom_col 中, position="dodge" 可以帮助创建“分组”列,而 coord_flip 将翻转 x 和 y 轴。

 library(tidyverse)
    #dummy data
    data <- tibble(participant = 1:30,
                   ethnicity = sample(c("e1", "e2"), 30, replace = T),
                   value = sample(-10:10, 30, replace = T),
                   enzyme = c(rep("enzyme1", 10), rep("enzyme2", 10), rep("enzyme3", 10)))
    #get mean value of 'value'
    data2 <- data %>% 
      group_by(enzyme, ethnicity) %>% 
      summarize(value = mean(value))

    ggplot()+
      geom_col(data = data2, aes(x = enzyme, 
                                y = value, 
                                fill = ethnicity),
               position = "dodge")+
      geom_hline(aes(yintercept = 0))+
      coord_flip()+
      theme_linedraw()

在此处输入图像描述

此外,如果您的数据在 3 个单独的列中包含酶的值,您应该使用 pivot_longer 从数据转换为长格式以使绘图更容易:

data_wide <- tibble(ethnicity = c("ethnicity1", "ethnicity2"),
                    enzyme1 = c(-1, -2), 
                    enzyme2 = c(0, 0),
                    enzyme3 = c(1, 2))
    # A tibble: 2 x 4
  ethnicity   enzyme1 enzyme2 enzyme3
  <chr>        <dbl>   <dbl>   <dbl>
1 ethnicity1      -1       0       1
2 ethnicity2      -2       0       2


   #transform to long
data_long <- data_wide %>% 
  pivot_longer(starts_with("enzyme"), "enzyme")

# A tibble: 6 x 3
  ethnicity   enzyme  value
  <chr>      <chr>   <dbl>
1 ethnicity1 enzyme1    -1
2 ethnicity1 enzyme2     0
3 ethnicity1 enzyme3     1
4 ethnicity2 enzyme1    -2
5 ethnicity2 enzyme2     0
6 ethnicity2 enzyme3     2

推荐阅读