2017-10-16 15 views
0

데이터를 플롯하려는 데이터가 geom_histogram이고 히스토그램에 geom_point으로 오버레이하여 몇 가지 점을 덧붙이고 싶습니다 geom_text 또는 annotate). geom_text와 텍스트를 추가하려고 지금 enter image description heregeom_histogram에 겹쳐진 geom_point 레이어에 geom_text/annotate 레이어 추가

을 그리고 :주는

g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) + 
    theme(legend.position="none") 

:

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

텍스트가 추가되지 6,

이 오류가 발생합니다.

아이디어가 있으십니까?

+0

Windows 10 R studio에서 오류가 발생하지 않았습니다. – 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")