【问题标题】:ggplot2: plotting the data in geom_tile for absence or presenceggplot2:在 geom_tile 中绘制数据是否存在或不存在
【发布时间】:2018-08-01 20:44:57
【问题描述】:

我正在尝试绘制数据

coords  chr pos ref alt GT  freq    sample
chr1_10126848   chr1    10126848    G   T   0/1 0.1 b1t2
chr1_1022375    chr1    1022375 C   T   0/1 0.018   b1t2
chr1_103025843  chr1    103025843   T   A   0/1 0.125   b1t2
chr1_103025922  chr1    103025922   T   C   0/1 0.314   b1t1
chr1_1042008    chr1    1042008 C   T   0/1 0.031   b1t2
chr1_1051632    chr1    1051632 G   A   0/1 0.03    b1t3
chr1_10599364   chr1    10599364    A   T   0/1 0.208   b1t3
chr1_10599364   chr1    10599364    A   T   0/1 0.308   b1t2
chr1_10599364   chr1    10599364    A   T   0/1 0.108   b1t1
chr1_1062578    chr1    1062578 T   C   0/1 0.207   b1t2
chr1_107480827  chr1    107480827   C   T   0/1 0.14    b1t3
chr1_107480827  chr1    107480827   C   T   0/1 0.54    b1t2
chr1_107480827  chr1    107480827   C   T   0/1 0.24    b1t1
chr1_107480957  chr1    107480957   C   A   0/1 0.214   b1t3
chr1_1084149    chr1    1084149 G   A   0/1 0.036   b1t2
.....

使用ggplot如下:

x<-read.table("trial2.txt", header=T, sep="\t")
ggplot(x,aes(sample, coords, fill=freq))+geom_tile()+ theme(axis.text.y = element_blank())+ scale_fill_gradient(low = "white", high = "red")  

我得到以下情节: 而我需要这样的东西:

任何人都可以指导我应该如何对数据进行排序,以便首先绘制所有样本中存在的坐标(y 轴),最后绘制每个样本唯一的坐标。

【问题讨论】:

    标签: r ggplot2 plot


    【解决方案1】:

    首先为每个coords 创建一个唯一数量的样本total - 您可以使用length(unique(sample)) 或更简洁地使用dplyr::n_distinct 来执行此操作。另一个概念是,您将希望reorder coords 通过这个新变量(在本例中,我将此新变量称为total):

    x %>%
      mutate_if(is.factor, as.character) %>%
      group_by(coords) %>%
      mutate(total = n_distinct(sample)) %>%
      ggplot(aes(sample, reorder(coords, total), fill = freq)) +
      geom_tile() +
      scale_fill_gradient(low = "white", high = "red") +
      theme(axis.text.y = element_blank())
    

    【讨论】:

      【解决方案2】:

      感谢 Jason 这么快回答。我也想通了,虽然没有你的那么复杂,但是很有效!

      x<-read.table("trial.txt", header=T, sep="\t") ## read input file
      x1<-merge(x, data.frame(table(coords = x$coords)), by = c("coords")) ## print frequency of each coordinate into new column "Freq". NOTE: "Freq" is different column than "freq"
      x2<-arrange(x1, Freq, sample) ## sort the data first by "Freq" and then by "sample"
      ggplot(x2,aes(sample, coords))+geom_tile(aes(fill = freq))+ scale_fill_gradient(low = "white", high = "red") + scale_y_discrete(limits=unique(x2$coords)) + theme(axis.text.y = element_blank(), plot.title = element_blank(),axis.title.x = element_blank(), axis.title.y = element_blank())   ## finally plot 
      

      【讨论】:

        猜你喜欢
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 2013-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多