Sander Van der Zeeuw
Sander Van der Zeeuw

Reputation: 1092

Change dots of a ggplot to text labels

Recently i asked a question about getting multiple graphs within 1 picture. I got some pretty good answers but 1 question still remains.

How to change dots from my scatter plot into labels? The plot looks like this enter image description here

Now i want all the black dots to be changed to the rownames of the data. The code i use for the plotting is as follows:

plotAll<-function(data){
  combs <- expand.grid(names(data), names(data))
  out <- do.call(rbind, apply(combs, 1, function(x) {
    tt <- data[, x]; names(tt) <- c("V1", "V2")
    tt <- cbind(tt, id1 = x[1], id2 = x[2])
  }))

  library(plyr)
  df.text=ddply(out[out$id1==out$id2,],.(id1,id2),summarise,
                pos=max(V1)-(max(V1)-min(V1))/2)
  out[out$id1==out$id2,c("V1","V2")]<-NA
  ggplot(data = out, aes(x = V2, y = V1)) + geom_point(alpha = 0.5) +
    facet_grid(id1 ~ id2,scales="fixed")+
    geom_text(data=df.text,aes(pos,pos,label=id1)) + geom_abline( slope=1 ) + 
    ggtitle("Corralation between measured & calculated affinities") +
    ylab("") + xlab("") + theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank())
}

I know i have to change the settings of geom_point(alpha=0.5) to something with geom_text(label=rownames(data)) But that deletes my axes and places the rownames onto the y-axes and into my datapoints. So probably i did something wrong with the lay out of the plot but what it is remains a question.

Upvotes: 3

Views: 940

Answers (1)

alexwhan
alexwhan

Reputation: 16026

So it turned out to be much more difficult than I thought... the basic problem is the NA values - geom_text can't handle them. That's pretty easy to fix by doing:

geom_text(data = out[!is.na(out$V1),], label = "test")

But when you go to do rownames as the label it gets problematic. I didn't figure out why, but got around it quickly by adding a label column to your dataframe. Full function below.

plotAll<-function(data){
  combs <- expand.grid(names(data), names(data))
  out <- do.call(rbind, apply(combs, 1, function(x) {
    tt <- data[, x]; names(tt) <- c("V1", "V2")
    tt <- cbind(tt, id1 = x[1], id2 = x[2])
  }))

  library(plyr)
  df.text=ddply(out[out$id1==out$id2,],.(id1,id2),summarise,
                pos=max(V1)-(max(V1)-min(V1))/2)
  out[out$id1==out$id2,c("V1","V2")]<-NA
  out$labels <- rownames(out)
  ggplot(data = out, aes(x = V2, y = V1)) + geom_text(data = out[!is.na(out$V1),], aes(label = labels)) +
    facet_grid(id1 ~ id2,scales="fixed")+
    geom_text(data=df.text,aes(pos,pos,label=id1)) + geom_abline( slope=1 ) + 
    ggtitle("Corralation between measured & calculated affinities") +
    ylab("") + xlab("") + theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank())
}
plotAll(data)

Upvotes: 1

Related Questions