简体   繁体   中英

Side-by-side pie charts of 2 matrices R

say you have 2 matrices m1 and m2 and each has equal an number of columns.

m1 = matrix(0, 10, 5, dimnames = list(c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"), c(1, 2, 3, 4, 5)))
m1[1,] = c(0,0,0,0,1)
m1[2,] = c(0,0,0,1,1)
m1[3,] = c(0,0,1,1,1)
m1[4,] = c(0,0,1,1,0)
m1[5,] = c(1,0,0,0,0)
m1[6,] = c(1,1,1,0,0)
m1[7,] = c(0,1,1,0,0)
m1[8,] = c(0,1,1,0,0)
m1[9,] = c(0,1,1,1,0)
m1[10,] = c(1,1,1,0,1)

m2 = matrix(0, 10, 5, dimnames = list(c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"), c(1, 2, 3, 4, 5)))
m2[1,] = c(0,0,0,0,1)
m2[2,] = c(0,0,0,1,1)
m2[3,] = c(0,0,1,1,1)
m2[4,] = c(0,0,1,1,0)
m2[5,] = c(1,0,0,0,0)
m2[6,] = c(1,1,1,0,0)
m2[7,] = c(0,1,1,0,0)
m2[8,] = c(0,1,1,0,0)
m2[9,] = c(0,1,1,1,0)
m2[10,] = c(1,1,1,0,1)

What I would like to see is a pie-chart comparison of these two matrices.

One way I can think is for each column, add each row, and then use those to get fractions for a pie chart.

sumcols <-function(x){
    for (i in 1:numcols(x)){
        sum <- sum(x[,i])
        sums.append(sum) #python here ...
    }
    return(sums)
}

so now, i can pass any matrix, get back a list of sums, which I assume now we can use to get a pie chart:

sums1 <- sumcols(m1)
sums2 <- sumcols(m2)
par(mfrow = c(1,2))
pie(c(sums1,sums2))

thank you for your help!

This will give you pie for 1st columns sums:

pie(c(colSums(m1)[1],colSums(m2)[1]))

I think barplot would be more informative:

barplot(c(colSums(m1),colSums(m2)), col=c(rep(1,ncol(m1)),rep(2,ncol(m1))))

UPDATE:

Try this:

#get col sums
m1_sums <- colSums(m1)
m2_sums <- colSums(m2)
#make negatives zero
m1_sums[m1_sums<0] <- 0
m2_sums[m2_sums<0] <- 0
#pie
par(mfrow = c(1,2))
pie(m1_sums,main="m1 - colSums")
pie(m2_sums,main="m2 - colSums")

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM