2

I plotted the contents of csv file (which has either 0's or 1's as elements) in the following way

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()

My data looks something like this, where I excluded row1 and column1. Now I'd like to get the sum of all 1's or 0's in each column and row and represent it at the end of the column and row respectively. I'd really appreciate any suggestions on how to do this.

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
abn
  • 1,353
  • 4
  • 28
  • 58
  • Your problem is not reproducible since you didn't include any sample data. Please read [how to make a great R reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for tips on best practice when asking for help. This is especially true with questions about plots since we can't see what you're looking at any other way. – MrFlick Oct 01 '14 at 21:35
  • @MrFlick Please find the edited question. – abn Oct 01 '14 at 21:38

1 Answers1

3

If you want to add the actual total values to the plot, then you have to make room for them and calculate them yourself. here's one such strategy. First, make sure "id" is a factor columns

gg$id<-factor(gg$id)

then

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()

will produce

enter image description here

If you had something else in mind, be more explicit about what you want the desired output to be.

MrFlick
  • 195,160
  • 17
  • 277
  • 295