Reputation: 31
My function:
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)
}
print(res)
}
I have code that generates histograms for me:
hist(Fluorescence_Intensity(X=1000, MEAN=2, SD=1, METHOD="rnorm"),xlim=c(0,40),col=scales::alpha('gray70',.4),border=F)
hist((Fluorescence_Intensity(X=1000, MEAN=30, SD=1, METHOD="rnorm")),add=T,col=scales::alpha('gray70'),border=F)
I want to correct my graphs so that, as in the picture, they show the mean green for which the histograms cut off at 95th percentile in blue for a lighter histogram as shown in the picture.I do not know how to do it, so please help me. I don't need colourful background.
Upvotes: 1
Views: 42
Reputation: 76460
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.
hist
object for each of the variables;hist
objects;type = "N"
);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
Upvotes: 1