M. 0.
M. 0.

Reputation: 55

For loop inside ggplot to add annotated text

I have rating data that I am making a geom_tile plot out of. I want to demonstrate the overall counts for each tile, as well as the proportion of each tile's counts that correspond to male and female ratings. I have 45 tiles, and my very cumbersome solution is to add 90 annotate layers from the contingency table (table) I used to create the plot.

all = as.data.frame(table(df$overall_score, df$difficulty_score))
m = profs %>% filter(sex == "male")
male = as.data.frame(table(m$overall_score, m$difficulty_score))
female = all - male

> all
   Var1 Var2  Freq
1     1    1   250
2   1.5    1    64
3     2    1   101
4   2.5    1    89
5     3    1   246
6   3.5    1   239
7     4    1   685
8   4.5    1  1015
9     5    1 10681

ggplot(all, aes(x = Var2, y = Var1)) + geom_tile(aes(fill = Freq)) +
    annotate("text", x = 0.75, y = 1, label = round(female$Freq[1] / 
    all$Freq[1]  * 100, 1), color = "red") +
    annotate("text", x = 1.25, y = 1, label = round(male$Freq[1]  / 
    all$Freq[1] * 100, 1), color = "white") +
    annotate("text", x = 0.75, y = 2, label = round(female$Freq[2] / 
    all$Freq[2]  * 100, 1), color = "red") +
    annotate("text", x = 1.25, y = 2, label = round(male$Freq[2]  / 
    all$Freq[2] * 100, 1), color = "white")...

enter image description here

I tried writing a for loop inside a toy data set, and while the plot rendered, the text didn't print on the plot:

z = data.frame(x = 1:10, y = 2:11)
ggplot(z, aes(x = x, y = y)) + geom_point() + for (i in 1:nrow(z)) {
annotate("text", x = 0.3, y = 3, label = "hi", color = "black")}

enter image description here

I can certainly add 90 annotate layers, but there must be a faster and less tedious way?

Upvotes: 1

Views: 683

Answers (1)

baptiste
baptiste

Reputation: 77124

Add one geom_text layer,

library(ggplot2)

d <- expand.grid(x=1:5,y=1:5)
d$z <- rnorm(nrow(d))
d$label <- sample(LETTERS, size = nrow(d), replace = TRUE)

ggplot(d, aes(x,y,fill=z)) + geom_tile() +
  geom_text(aes(label=label))

Edit: to add a binary colour legend

library(ggplot2)

d <- expand.grid(x=1:5,y=1:5)
d$z <- rnorm(nrow(d))
d$f <- sample(LETTERS, size = nrow(d), replace = TRUE)
d$m <- sample(LETTERS, size = nrow(d), replace = TRUE)

dd <- tidyr::gather(d, gender, label, -x,-y,-z)
ggplot(dd, aes(x,y,fill=z)) + geom_tile() +
  geom_text(aes(label=label,colour=gender, hjust = ifelse(gender=="f",0,1))) +
  scale_colour_manual("gender", values=c("pink","green"))

Upvotes: 4

Related Questions