我想要在geom_histogram
中绘制数据,并且我想在{(1}}的直方图上叠加几个点,然后对它们进行注释(使用{{1} }或geom_point
)。
这里是直方图和点数:
geom_text
覆盖我使用的点:
annotate
现在尝试使用#data
library(ggplot2)
set.seed(10)
df <- data.frame(id = LETTERS, val = rnorm(length(LETTERS)))
#points I want to overlay
selected.ids <- sample(LETTERS, 3, replace = F)
cols <- rainbow(length(selected.ids))
selected.df <- data.frame(id=selected.ids, col=cols, stringsAsFactors = F)
selected.df$x <- df$val[which(df$id %in% selected.ids)]
selected.df <- selected.df[order(selected.df$x),]
selected.df$col <- factor(selected.df$col, levels=cols)
#building the histogram
g <- ggplot(df, aes(x = val)) + geom_histogram(bins = 10, colour = "black", alpha = 0, fill = "#FF6666")
#finding the x,y locations of the points:
g.data <- ggplot_build(g)$data[[1]]
g.breaks <- c(g.data$xmin, tail(g.data$xmax, n=1))
selected.df$y <- g.data$count[findInterval(selected.df$x, g.breaks)]
添加文字:
g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) +
theme(legend.position="none")
引发此错误:
geom_text
使用g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) +
annotate("text",size=2,x=selected.df$x,y=selected.df$y,label=selected.df$id)+
theme(legend.position="none")
:
Error in unique.default(x, nmax = nmax) :
unique() applies only to vectors
未添加任何文字。
有什么想法吗?
答案 0 :(得分:1)
我认为你要做的就是这样。 geom_text应该与所选数据的geom_point相同。
g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) +
geom_text(data=selected.df, aes(x=x, y=y, label=id))+
theme(legend.position="none")