Here are two ways.
The first is exactly like I said in my comment to the question. Compute the statistics to be plotted and then plot the vertical lines with abline
. The rest of the code is almost a copy&paste from the question.
Fluorescence_Intensity <- function(X, MEAN, SD, METHOD){
if(METHOD=="rnorm"){
res <- rnorm(X, MEAN, SD)
}
if(METHOD=="dnorm"){
res <- dnorm(X, MEAN, SD)
}
if(METHOD=="qnorm"){
res <- qnorm(X, MEAN, SD, METHOD, LOWER.TAIL=NULL, LOG.P=NULL)
}
res
}
set.seed(2022) # make the code reproducible
x <- Fluorescence_Intensity(X = 1000, MEAN = 2, SD = 1, METHOD = "rnorm")
y <- Fluorescence_Intensity(X = 1000, MEAN = 30, SD = 1, METHOD = "rnorm")
x.bar <- mean(x)
y.bar <- mean(y)
x.q95 <- quantile(x, 0.95)
hist(x, xlim = c(0, 40), col = scales::alpha('gray70', 0.4), border = FALSE)
hist(y, add = TRUE, col = scales::alpha('gray70'), border = FALSE)
abline(v = c(x.bar, y.bar, x.q95), col = c("green", "green", "blue"), lwd = 2)

Created on 2022-11-04 with reprex v2.0.2
The second way draws the blue background rectangle.
- Create a
hist
object for each of the variables;
- get the axis limits, the x axis directly from the data, the y axis limits from those
hist
objects;
- open the plot with the right dimensions but plot nothing (
type = "N"
);
- draw the grid lines;
- draw the background rectangle;
- and finally the histograms and vertical lines.
Note that the histograms code is a simplified version of the question's code. Above I have left it as is but there is no need for calls to scales::alpha
.
hx <- hist(x, plot = FALSE)
hy <- hist(y, plot = FALSE)
xlim <- range(c(x, y))
ylim <- c(0, max(hx$counts, hy$counts))
plot(1, type = "n", xlim = xlim, ylim = ylim,
xlab = "Fluorescence Intensity", ylab = "Frequency")
grid()
rect(xlim[1] - 10, -10, x.q95, ylim[2] + 10, col = scales::alpha('lightblue', 0.4), border = FALSE)
hist(x, add = TRUE, col = 'gray70', border = FALSE)
hist(y, add = TRUE, col = 'gray70', border = FALSE)
abline(v = c(x.bar, y.bar, x.q95), col = c("green", "green", "blue"), lwd = 2)

Created on 2022-11-04 with reprex v2.0.2