0
我有我想要在geom_histogram
中绘制的数据,并且它有几个要叠加在直方图上的点,然后对它们进行注释(用geom_text
或annotate
)。将geom_text/annotate图层添加到geom_histogram上覆盖的geom_point图层
这里的直方图和点:
#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
而且随着annotate
:
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")
没有文字添加。
有什么想法?
Windows 10 R工作室并没有给我错误。 – Suren
'annotate()'为我工作。您可能想要增加文字大小? –