我以以下方式绘制了csv文件的内容(具有0或1的元素)
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
如果要将实际总值添加到绘图中,则必须为它们腾出空间并自己计算。这是一种这样的策略。首先,确保“ 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()
将产生
如果您有其他想法,请更明确地说明所需的输出是什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句