Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.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 使用position_dodge时出现geom_文本问题_R_Ggplot2 - Fatal编程技术网

R 使用position_dodge时出现geom_文本问题

R 使用position_dodge时出现geom_文本问题,r,ggplot2,R,Ggplot2,我看到了答案,但无法复制 我的数据如下所示: df = data.frame(x = rep(sample(letters, 4), 2), y = round(runif(8,1,100),0), z = c(rep("group1",4), rep("group2",4))) # I then add a 'percent' column like so: df$perc[1:4] = df$y[1:4] / sum(d

我看到了答案,但无法复制

我的数据如下所示:

df = data.frame(x = rep(sample(letters, 4), 2), 
                y = round(runif(8,1,100),0), 
                z = c(rep("group1",4), rep("group2",4)))

# I then add a 'percent' column like so:

df$perc[1:4] = df$y[1:4] / sum(df$y[1:4])
df$perc[5:8] = df$y[5:8] / sum(df$y[5:8])

# Which I then convert like so:
df$perc = paste(round(df$perc * 100, 1), "%", sep="")

# The ggplot:
library(ggplot2)

ggplot(df) + 
geom_bar(aes(z, y, fill=x), position="dodge", stat="identity") + 
geom_text(aes(z,y,label=perc), position=position_dodge(width=1), size=4)
结果:


我不知道我做错了什么。

只要一个小改动就可以解决问题。您需要在
geom_文本(aes(…)
调用中指定
group=x

ggplot(df) + 
geom_bar(aes(z, y, fill=x), position=position_dodge(width=1), stat="identity") + 
geom_text(aes(z,y,label=perc, group=x), position=position_dodge(width=1), size=4)

或将
fill=x
移动到
ggplot
中的“顶层”。然后这个规避变量也会被继承到
geom\u text
<代码>道奇