【问题标题】:Reverse grouped barplot in RR中的反向分组条形图
【发布时间】:2020-04-20 21:25:31
【问题描述】:

我有 35 位参与者的数据,例如

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

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

谢谢

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    这将通过酶和伦理对虚拟数据组进行汇总并获得“值”列的平均值,然后绘制图。在 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
    

    【讨论】:

    • 谢谢!但在 Y 轴上,我们应该有代谢物名称,如(A、B 和 C),在 X 轴上,我们应该有这些代谢物值(表中列出的值)。
    • 更新了答案,因此酶在 y 轴上,值在 x 轴上。这些酶按种族分开和分组。
    • 感谢您的帮助。我使用以下命令分别制作了 foe 种族 1 和种族 2 的图。您是否知道如何更改代码以使用不同的颜色来减少和增加值(例如,大于零和小于零)?谢谢。 data_long1=子集(data_long,ethnicity==“ethnicity1”)ggplot()+ geom_col(data = data_long1,aes(x =酶,y =值),位置=“闪避”)+ geom_hline(aes(yintercept = 0)) + coord_flip()+ theme_linedraw()
    • 这是我第二个问题的答案:data_long1[["sign"]] = ifelse(data_long1[["value"]] >= 0, "positive", "negative") ggplot( )+ geom_col(data = data_long1, aes(x = 酶, y = value,fill = sign))+ geom_hline(aes(yintercept = 0))+ coord_flip()+ theme_linedraw()+ geom_bar() + scale_fill_manual(values = c("正" = "绿", "负" = "红"))
    猜你喜欢
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多