2017-10-16 139 views
0

我有我想要在geom_histogram中繪製的數據,並且它有幾個要疊加在直方圖上的點,然後對它們進行註釋(用geom_textannotate)。將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") 

這給: enter image description here

現在試圖將文本與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") 

沒有文字添加。

有什麼想法?

+0

Windows 10 R工作室並沒有給我錯誤。 – Suren

+0

'annotate()'爲我工作。您可能想要增加文字大小? –

回答

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