ockstackerflow
ockstackerflow

Reputation: 59

how to use stat_peaks with a density plot in ggplot

I have a graph that looks like so, and want to plot the peaks on it: ggplot density graph

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

Answers (1)

mrhd
mrhd

Reputation: 1076

This question has been answered before.

You can do this in a three-step process:

  1. Plot the densities
  2. Generate a "build" object of the plot using ggplot_build
  3. Extract the peaks from the "build" object and plot them
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

Related Questions