R- How to plot correct pie charts in haploNet haplotyp Networks {pegas} {ape} {adegenet}

不想你离开。 提交于 2019-12-01 11:28:22
hugo

I've struggled with the same issue, but believe I came up with a solution.

The problem is that the step making the table of haplotype counts per "population" orders the haplotypes alphabetically. So, for example, haplotype "IX" comes before "V". On the other hand, the function haplotype() sorts the haplotypes by their "numerical" order. And this is what creates a discrepancy when plotting.

This can be solved by sorting the haplotype object by "label", as explained in ?haplotype help.

I'll use the woodmouse example data to exemplify:

# Sample 9 distinct haplotypes
library(pegas)
data(woodmouse)
x <- woodmouse[sample(9, 100, replace = T), ]

To simplify, I create a function to create the count table of haplotypes (based on this post):

countHap <- function(hap = h, dna = x){
    with(
        stack(setNames(attr(hap, "index"), rownames(hap))),
        table(hap = ind, pop = attr(dna, "dimnames")[[1]][values])
    )
}

Now, let's see the result without sorting haplotypes:

h <- haplotype(x) # create haplotype object
net <- haploNet(h) # create haploNet object

plot(net, pie = countHap(), size = attr(net, "freq"), legend = T)

Now, let's look at our count table, to check these results:

countHap(h, x)

      pop
hap    No0906S No0908S No0909S No0910S No0912S No0913S No304 No305 No306
  I          0       0       0       0       0       0     0     8     0
  II         0       0       0       0       0       0     9     0     0
  III        0       0       0       0       0       0     0     0    10
  IV        16       0       0       0       0       0     0     0     0
  IX         0       0       0       0       0       8     0     0     0
  V          0      12       0       0       0       0     0     0     0
  VI         0       0      10       0       0       0     0     0     0
  VII        0       0       0      13       0       0     0     0     0
  VIII       0       0       0       0      14       0     0     0     0

Things do not match: for example, haplotype "V" should occur in individual "No0908S", but instead is coloured as individual "No0913S" (which should be the label for haplotype "IX").

Now, let's sort haplotypes:

h <- haplotype(x)
h <- sort(h, what = "labels") # This is the extra step!!
net <- haploNet(h)

plot(net, pie = countHap(), size = attr(net, "freq"), legend = T)

And all is well now!

Extra:

Although this is not requested by the OP, I thought of leaving it here if it is of interest for anyone else. Sometimes, I find it convenient to label haplotypes by their frequency. This can be done by changing the haplotype labels to be equal to their frequencies:

attr(h, "labels") <- attr(h, "freq")
plot(net, pie = countHap(), size = attr(net, "freq"), legend = T)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!