问题
I have an R plot in which I want to show that IF the "red" curve (which is now at the bottom of plot not showing correctly) be multiplied by a constant, it can match the "blue" curve currently showing.
I'm wondering how best I can scale up the "red" curve so that it exactly matches the "blue" curve?
(My R code is provided below the picture.)
Here is my R code:
SIGMA = 2 # Population SIGMA known
observations = seq(1, 30) # observations drawn
n = length(observations) # number of observations
x_bar = mean(observations) # mean of observations
SE = SIGMA / sqrt(n) # 'S'tandard 'E'rror of the mean
x.min = x_bar - 4*SE
x.max = x_bar + 4*SE
Like = function(x) sapply(lapply(x, dnorm, x = observations, SIGMA), prod) # multiplication of densities to obtain Likelihood values
curve(dnorm(x, x_bar, SE), from = x.min, to = x.max, col = 'blue', lwd = 3, lty = 2 ) # Sampling Distribution of x_bar
curve(Like, from = x.min, to = x.max, col = 'red', lwd = 3, add = T) # Likelihood function of MU
回答1:
Basically, we need to scale values of cc2$y
proportionally such that the scaled values of cc2$y
have the same range (minimum and maximum) as cc1$y
. I have used rescale
function of scales
package to do that
# Sampling Distribution of x_bar
cc1 = curve(dnorm(x, x_bar, SE), from = x.min, to = x.max, col = 'blue', lwd = 3, lty = 2 )
# Likelihood function of MU
cc2 = curve(Like, from = x.min, to = x.max, col = 'red', lwd = 3, add = T)
library(scales)
scale_factor = mean(rescale(cc2$y, range(cc1$y)) / cc2$y) #APPROXIMATE
plot(cc1, type = "l")
lines(cc2$x, cc2$y * scale_factor, col = "red")
Here is the rescale2
modified from rescale
function of scales
library if you want to use it without loading the library
rescale2 = function (x, to = c(0, 1))
{
(x - min(x))/diff(range(x)) * diff(to) + to[1]
}
来源:https://stackoverflow.com/questions/43688786/scaling-up-a-curve-line-such-that-it-can-be-shown-along-side-another-curve-line