2014-10-01 27 views
2

獲得在情節的行和列的總和我繪製的CSV文件的內容(其無論是0或1的爲元素)以下列方式如何,使用R

mat <- read.csv("trial.csv", header=T, row.names=1) 
vec <- as.vector(as.matrix(mat)) 
varieties = names(mat) 
matVar = matrix(vec, ncol = length(varieties), nrow = length(attr(mat, "row.names"))) 
library(ggplot2) 
require(reshape2) 
mat$id <- rownames(mat) 
gg <- melt(mat) 
ggplot(gg, aes(x=id,y=variable,fill=value))+ 
    geom_tile()+ 
    scale_fill_gradient(low="red",high="white")+ 
    theme(axis.text.x = element_text(angle=90))+ 
    coord_flip() 

我的數據看起來是這樣的,我排除了row1和column1。現在我想要得到每列和每行中所有1或0的總和,並分別表示它們在列和行的末尾。我真的很感謝有關如何做到這一點的任何建議。

h1, h2, h3, h4, h5, h6, h7, h8, h9 
a, 1, 1, 1, 0, 1, 1, 0, 1 
b, 0, 1, 1, 1, 0, 0, 0, 0 
c, 1, 0, 0, 1, 1, 1, 1, 1 
d, 1, 0, 1, 0, 0, 0, 1, 0 
e, 1, 0, 0, 0, 0, 1, 0, 0 
f, 1, 1, 0, 0, 0, 0, 0, 0 
g, 0, 0, 0, 0, 0, 0, 0, 0 
h, 0, 0, 0, 0, 0, 1, 1, 0 
+0

由於您沒有包含任何樣本數據,因此您的問題無法重現。請閱讀[如何使一個偉大的R可重現的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)尋求幫助時的最佳做法技巧。關於情節的問題尤其如此,因爲我們無法以任何其他方式看到你在看什麼。 – MrFlick 2014-10-01 21:35:30

+0

@MrFlick請找到編輯後的問題。 – abn 2014-10-01 21:38:46

回答

1

如果您想要將實際總值添加到圖中,則必須爲他們騰出空間並自行計算。這是一個這樣的策略。首先,確保 「ID」 是一個因素列

gg$id<-factor(gg$id) 

然後

ggplot(gg, aes(x=id,y=variable))+ 
    geom_tile(aes(fill=value))+ 
    scale_fill_gradient(low="red",high="white")+ 
    geom_text(aes(label=value), data=cbind(aggregate(value~id, gg, sum), variable="total")) + 
    geom_text(aes(label=value), data=cbind(aggregate(value~variable, gg, sum), id="total")) + 
    theme(axis.text.x = element_text(angle=90))+ 
    scale_x_discrete(limits=c(levels(gg$id), "total"))+ 
    scale_y_discrete(limits=c(levels(gg$variable), "total"))+ 
    coord_flip() 

會產生

enter image description here

如果你腦子裏想別的東西,更加明確什麼你想要的輸出是。

+0

完美!謝謝。 – abn 2014-10-01 22:04:14