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")
をそして今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()'が私のために働いていました。テキストサイズを大きくすることができますか? –