Reputation: 59
I have a graph that looks like so, and want to plot the peaks on it:
this is my current code:
ggplot(df,aes(x=xval,fill=sample)) +
geom_density(alpha=.5)+
xlim(c(median(xval)-0.001,median(xval)+0.001))+
labs(title=paste0("Title ",datetoday),x="intensity",fill="concentration")+
ggsave((paste0("file ",datetoday,".png")))
whenever I try to add stat_peaks to my graph, it gives me the error 'Error: stat_peaks requires the following missing aesthetics: y' - but I'm not sure how to set the y value to the density.
TIA
Upvotes: 0
Views: 1155
Reputation: 1076
This question has been answered before.
You can do this in a three-step process:
ggplot_build
library(ggplot2)
library(ggpmisc)
p <- ggplot(df,aes(x=xval,fill=sample)) +
geom_density(alpha=.5)+
xlim(c(median(xval)-0.001,median(xval)+0.001))+
labs(title=paste0("Title ",datetoday),x="intensity",fill="concentration")
pb <- ggplot_build(p)
p + stat_peaks(
data = pb[['data']][[1]], # take a look at this object
aes(x = x, y = density),
colour = "red",
size = 3
)
ggsave((paste0("file ",datetoday,".png")))
Upvotes: 1