I wan to use ggplot
to plot a histogram (or a step plot using stat_bin
) and overlay a few points on it using geom_point
.
Here's a base
implementation:
library(plotrix)
set.seed(10)
df <- data.frame(id=LETTERS,val=rnorm(length(LETTERS)))
selected.ids <- sample(LETTERS,3,replace=F)
h <- hist(df$val,plot=F,breaks=10)
cols <- sapply(rainbow(length(selected.ids)),function(x) color.id(x)[1])
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$y <- h$counts[findInterval(selected.df$x,h$breaks)]
selected.df$col <- factor(selected.df$col,levels=cols)
plot(h)
segments(x0=selected.df$x,x1=selected.df$x,y0=selected.df$y,y1=selected.df$y,cex=18,lwd=8,col=selected.df$col)
which gives:
However when I try ggplot
:
ggplot(df,aes(x=val))+geom_histogram(bins=10,colour="black",alpha=0,fill="#FF6666")+geom_point(data=selected.df,aes(x=x,y=y,colour=factor(col)),size=2)+scale_fill_manual(values=levels(selected.df$col),labels=selected.df$id,name="id")+scale_colour_manual(values=levels(selected.df$col),labels=selected.df$id,name="id")
The points and histogram are misaligned:
Ideally I would like to plot it using a step plot:
ggplot(df,aes(x=val))+stat_bin(geom="step",bins=10)+geom_point(data=selected.df,aes(x=x,y=y,colour=factor(col)),size=2)+scale_fill_manual(values=levels(selected.df$col),labels=selected.df$id,name="id")+scale_colour_manual(values=levels(selected.df$col),labels=selected.df$id,name="id")
Which looks pretty much like the geom_histogram
but also I'd also like to have the ends of the line touch the y=0 line.
So I do I get the correctly in a step plot using the stat_bin?