Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用于在ggplot内循环以添加注释文本_R_For Loop_Ggplot2 - Fatal编程技术网

R 用于在ggplot内循环以添加注释文本

R 用于在ggplot内循环以添加注释文本,r,for-loop,ggplot2,R,For Loop,Ggplot2,我有评级数据,我正在制作一个geom_tile绘图。我想展示每个瓷砖的总计数,以及每个瓷砖的计数与男性和女性评级相对应的比例。我有45个瓷砖,我非常麻烦的解决方案是从用于创建绘图的列联表(表)中添加90个注释层 all = as.data.frame(table(df$overall_score, df$difficulty_score)) m = profs %>% filter(sex == "male") male = as.data.frame(table(m$overall_sc

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

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

我尝试在一个玩具数据集中写一个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")}


我当然可以添加90个
注释层
但必须有一种更快、更省力的方法?

添加一个geom_文本层

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

d好极了!我可以添加两层,每种性别(和颜色)一层,并
轻推_x
来移动它们。现在,有没有办法制作第二个图例,说明颜色对应于,比如说,“%男性”和“%女性”,显示在绘图文本的颜色中?我似乎无法让
缩放\u颜色\u手册
显示任何内容。
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"))