0

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

1 Answers1

1

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")))
mrhd
  • 1,036
  • 7
  • 16
  • Thanks, I tried that code but got this error: 'Error: Aesthetics must be either length 1 or the same as the data (2560): fill'. Which I assume is because I have multiple fills and the data in the previous question is only a single fill. – ockstackerflow Nov 07 '19 at 13:39
  • Yes, this is probably due to the grouping by `sample`, but it is a bit difficult to reproduce without the data frame you used. Does it work if you replace `aes(x = x, y = density)` with `aes(x = x, y = density, fill = NA)`? – mrhd Nov 07 '19 at 16:14