在R中使用正x轴绘制两组水平条形图

时间:2019-07-11 15:58:07

标签: r ggplot2 bar-chart

给出以下矩阵

df <- matrix(c(10,8, 20, 6, 20, 25,"exp", "cnt", "exp","cnt","exp","cnt","gene1","gene1","gene2","gene2","gene3","gene3"), 
nrow=6, dimnames=list(c("1", "2", "3","4","5","6"),c("Abundance", "Group","gene")  )) 

我想水平绘制两组“ exp”和“ cnt”的条形图,用零点的垂直线隔开,y轴显示对应于每个基因的正值,x轴上显示基因名称。 这里是一个例子:

enter image description here

我使用ggplot尝试了以下代码,但是没有用。

ggplot(df, aes(x=gene))+
  geom_bar(aes(y=Abundance, fill="exp"), stat="identity")+
  geom_bar(aes(y=-Abundance, fill="cnt"),  stat="identity")+
  scale_fill_manual("Group",values=c(exp="red",cnt="green"))+
  labs(y="Abundance")+coord_flip()

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您的代码正确,但是您遇到的问题是您将data.frame做成矩阵。 ggplot仅将data.frames作为输入。第二个问题是矩阵只能容纳一种数据类型,因此它会将所有内容都转换为字符(因此当您尝试使“丰度”为负数时会产生错误)

将数据放在data.frame中,它将起作用:

library(tidyverse)

df <- tibble(Abundance = c(10, 8, 20, 6, 20, 25), 
             Group = c("exp", "cnt", "exp", "cnt", "exp", "cnt"),
             gene = rep(paste0("gene", 1:3), each = 2))
df
#> # A tibble: 6 x 3
#>   Abundance Group gene 
#>       <dbl> <chr> <chr>
#> 1        10 exp   gene1
#> 2         8 cnt   gene1
#> 3        20 exp   gene2
#> 4         6 cnt   gene2
#> 5        20 exp   gene3
#> 6        25 cnt   gene3

ggplot() + 
    geom_bar(data = filter(df, Group == "cnt"), 
             aes(x = gene, y = Abundance, fill = Group),
             stat = 'identity', position = 'stack') + 
    geom_bar(data = filter(df, Group == "exp"), 
             aes(x = gene, y = -Abundance, fill = Group), 
             stat = 'identity', position = 'stack') + 
    coord_flip() + 
    geom_hline(yintercept = 0, linetype = "dashed")

reprex package(v0.3.0)于2019-07-11创建