for ggplot里面的循环添加带注释的文本

时间:2017-10-22 05:12:14

标签: r for-loop ggplot2

我有评分数据,我正在制作geom_tile图。我想展示每个瓷砖的总体计数,以及每个瓷砖的数量与男性和女性评级相对应的比例。我有45个瓷砖,我非常麻烦的解决方案是在用于创建绘图的列联表(annotate)中添加90个table图层。

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

我尝试在玩具数据集中编写for循环,并且在渲染图时,文本没有打印在情节上:

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

我当然可以添加90个annotate图层,但必须有更快,更乏味的方法吗?

1 个答案:

答案 0 :(得分:3)

添加一个geom_text图层

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

编辑:添加二进制颜色图例

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