R 使用ggplot2在直方图上添加箭头

R 使用ggplot2在直方图上添加箭头,r,graphics,ggplot2,R,Graphics,Ggplot2,尝试使用ggplot2将箭头添加到堆叠的直方图时遇到一些问题 首先,我使用 set.seed(1234) df <- data.frame( sex=factor(rep(c("F", "M"), each=200)), weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5))) ) set.seed(1234) df您的第一次尝试似乎效果良好,警告是无害的。第一个情节看起来有什么问题吗?正如@ei

尝试使用ggplot2将箭头添加到堆叠的直方图时遇到一些问题

首先,我使用

set.seed(1234)

df <- data.frame(
  sex=factor(rep(c("F", "M"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5)))
)
set.seed(1234)

df您的第一次尝试似乎效果良好,警告是无害的。第一个情节看起来有什么问题吗?正如@eipi10所说:你可以忽略警告。或者通过
ymax=…count..
交换
y=…count..
。此外,
x=52,xend=52,y=30,yend=0
不一定需要在aes中包装。。。
p <- ggplot(df, aes(x=weight)) +
  geom_histogram(aes(fill=sex, color=sex), position="stack", alpha=0.5, binwidth=5) +
  stat_bin(aes(y=..count.. + 2 , label=..count..), drop="TRUE", geom="text", binwidth=5)

p + geom_segment(aes(x=52, xend=52, y=30, yend = 0), colour="darkblue", size=1, arrow = arrow(length = unit(0.5, "cm")))
p <- ggplot(df, aes(x=weight, ymax=..count..)) +     geom_histogram(aes(fill=sex, color=sex), position="stack", alpha=0.5, binwidth=5) + stat_bin(aes(y=..count.. + 2 , label=..count..), drop="TRUE", geom="text", binwidth=5)

p + geom_segment(aes(x=52, xend=52, y=30, yend = 0), colour="darkblue", size=1, arrow = arrow(length = unit(0.5, "cm")))