如何在 R 中使用 ggplot2 创建背靠背直方图?

时间:2021-01-15 03:35:31

标签: r ggplot2 histogram

我有一个名为 dfTP_FP,我想使用 ggplot2 基于 Group 列创建一个背靠背(镜像)直方图。

 `TP_FP`
           Value        Group        
            <dbl>       <chr>         
         1 -0.00540   False positive
         2  0.331     True positive
         3 -1.11      False positive
         4  1.4365    False positive
         5 -0.586     True positive
         6  1.26      True positive
         7  0.5463    False positive
         8  3.245     False positive
         9 -0.950     False positive
        10 10.4354    True positive

我尝试了以下方法:

ggplot(TP_FP, aes(x=x)) +
      geom_histogram(aes(x=Value, y = -..density.., fill= Group == "False positive"),col="black", binwidth = 0.1) +
      geom_histogram( aes(x=Value,y = ..density.., fill= Group =="True positive"),col="black", binwidth = 0.1) +
      labs(x="R Ratio", y="Number of proteins") +
      theme_bw() + theme(legend.position="right")

我希望得到一个像底部那样的合并直方图。

This is what I've got.

This is what I would expect

1 个答案:

答案 0 :(得分:2)

喜欢吗?

library(tidyverse)
TP_FP <- tribble(~Value, ~Group,        
                -0.00540, "False positive",
                0.331, "True positive",
                -1.11, "False positive",
                1.4365, "False positive",
                -0.586, "True positive",
                1.26, "True positive",
                0.5463, "False positive",
                3.245, "False positive",
                -0.950, "False positive",
                10.4354, "True positive")

ggplot() +
  geom_histogram(data = TP_FP %>% filter(Group == "False positive"),
                 aes(y = -(..density..), x = Value, fill = Group),
                 col = "black", binwidth = 0.1) +
  geom_histogram(data = TP_FP %>% filter(Group == "True positive"),
                 aes(y = ..density.., x = Value, fill = Group),
                 col = "black", binwidth = 0.1) +
  labs(x = "R Ratio", y = "Number of proteins") +
  theme_bw() + theme(legend.position = "right")

example.png