2017-10-16 9 views
0

私はgeom_histogramにプロットしたいデータを持っており、ヒストグラムにオーバーレイしたい点がgeom_pointであり、 geom_textまたはannotateのいずれか)。ここでgeom_histogramにオーバーレイされた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") 

います: 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") 
関連する問題