Plotting power plot in R without using ggplot2()? - r

Having trouble creating a plot of different power functions for different alpha levels. This is what I have currently but I cannot figure out how to create the multiple lines representing the smooth power function across different alpha levels:
d <- data.frame()
for (s in seq(0,.5,.05)) {
for (n in seq(20,500,by=20)){
d <- rbind(d,power.t.test(n=n,delta = 11,sig.level=s,sd= 22.9))
}
}
d$sig.level.factor <-as.factor(d$sig.level)
plot(d$power~d$n, col=d$sig.level.factor)
for i in length(sig.level.factor){
lines(d$n[d$sig.level.factor==d$sig.level.factor[i]],d$power[d$sig.level.factor==d$sig.level.factor[i]], type="l", lwd=2, col=colors[n])
}
for (i in 1:length(seq(0,.5,.05))){
lines(d$n[d$sig.level.factor==d$sig.level[i]], d$power, type="l", lwd=2, col=colors[i])
}
for (i in 1:length(d$sig.level.factor)){
lines(d$n[d$sig.level.factor==i], d$power[d$sig.level.factor==i], type="l", lwd=2, col=colors[i])
}
My goal is to create the lines that will show the smooth curves connecting all the points that contain equivalent alpha values across different sample sizes.

Slightly late answer but hope you can still use it. You can create a matrix of results over n and significance levels using sapply and then plot everything in one go using the super useful function matplot:
n <- seq(20, 300, by=10)
alphas <- seq(0, .25, .05)
res <- sapply(alphas, function(s) {power.t.test(n=n, delta=11, sig.level=s, sd= 22.9)$power})
matplot(n, res, type="l", xlab="Sample size", ylab="Power")
There is one annoying "feature" of power.t.test and power.prop.test and that is that it is not fully vectorized over all arguments. However, your situation, where the output is the power makes it easier.

Related

Plot ranges when plotting multiple things

R will automatically determine the plot ranges (xlim, ylim) from the first plot() call. But when you are plotting multiple things on a single plot, the subsequent calls to plot() might not fit in the frame, as in this case:
mu <- 8
sd <- 8
plot(function (x) dnorm(x, mu, sd, log = TRUE), xlim = c(0, 10)) # log likelihood
plot(function (x) (mu-x)/sd^2, col = "green", add = TRUE, xlim = c(0, 10)) # derivative log likelihood
I know I could first determine the ranges of all plot components myself and then min and max them together and pass the range to the first plot() call... but it is sooo inconvenient... and results in R scripts which are bulky and not easy to read.
Is there some simple way to handle this in R, am I missing something? I am sure libraries like ggplot or lattice have better solutions, would be interesting to see them, but I strongly prefer solution with the base R. Thanks! :)
EDIT: is it possible something like to defer the plotting of the plot until I call the last plot() and then plot everything? :-) This could be very elegant and the code would stay nicely compact :)
You could adapt your approach a little and define the functions beforehand.
fun1 <- function(x) dnorm(x, mu, sd, log=TRUE)
fun2 <- function(x) (mu-x)/sd^2
Then you easily may calculate the range of everything in the desired xlim of the plot – here 0:10.
y.range <- range(sapply(0:10, function(x) c(fun1(x), fun2(x))))
Finally rather use the already defined functions than repeat them in the plot() call. NB you may be looking for curve(), but it also works with plot() in this case.
curve(fun1, xlim=c(0, 10), ylim=y.range)
curve(fun2, col="green", add=TRUE, xlim=c(0, 10))
How about something along this line:
plot(function (x) dnorm(x, mu, sd, log = TRUE), xlim = c(0, 10)) # log likelihood
par(new=TRUE)
plot.function(function (x) (mu-x)/sd^2, col = "green", axes=FALSE, ann=FALSE) # derivative log
axis(side = 4)
Output

Multiple plots using curve() function (e.g. normal distribution)

I am trying to plot multiple functions using curve(). My example tries to plot multiple normal distributions with different means and the same standard deviation.
png("d:/R/standardnormal-different-means.png",width=600,height=300)
#First normal distribution
curve(dnorm,
from=-2,to=2,ylab="d(x)",
xlim=c(-5,5))
abline(v=0,lwd=4,col="black")
#Only second normal distribution is plotted
myMean <- -1
curve(dnorm(x,mean=myMean),
from=myMean-2,to=myMean+2,
ylab="d(x)",xlim=c(-5,5), col="blue")
abline(v=-1,lwd=4,col="blue")
dev.off()
As the curve() function creates a new plot each time, only the second normal distribution is plotted.
I reopened this question because the ostensible duplicates focus on plotting two different functions or two different y-vectors with separate calls to curve. But since we want the same function, dnorm, plotted for different means, we can automate the process (although the answers to the other questions could also be generalized and automated in a similar way).
For example:
my_curve = function(m, col) {
curve(dnorm(x, mean=m), from=m - 3, to=m + 3, col=col, add=TRUE)
abline(v=m, lwd=2, col=col)
}
plot(NA, xlim=c(-10,10), ylim=c(0,0.4), xlab="Mean", ylab="d(x)")
mapply(my_curve, seq(-6,6,2), rainbow(7))
Or, to generalize still further, let's allow multiple means and standard deviations and provide an option regarding whether to include a mean line:
my_curve = function(m, sd, col, meanline=TRUE) {
curve(dnorm(x, mean=m, sd=sd), from=m - 3*sd, to=m + 3*sd, col=col, add=TRUE)
if(meanline==TRUE) abline(v=m, lwd=2, col=col)
}
plot(NA, xlim=c(-10,10), ylim=c(0,0.4), xlab="Mean", ylab="d(x)")
mapply(my_curve, rep(0,4), 4:1, rainbow(4), MoreArgs=list(meanline=FALSE))
You can also use line segments that start at zero and stop at the top of the density distribution, rather than extending all the way from the bottom to the top of the plot. For a normal distribution the mean is also the point of highest density. However, I've used the which.max approach below as a more general way of identifying the x-value at which the maximum y-value occurs. I've also added arguments for line width (lwd) and line end cap style (lend=1 means flat rather than rounded):
my_curve = function(m, sd, col, meanline=TRUE, lwd=1, lend=1) {
x=curve(dnorm(x, mean=m, sd=sd), from=m - 3*sd, to=m + 3*sd, col=col, add=TRUE)
if(meanline==TRUE) segments(m, 0, m, x$y[which.max(x$y)], col=col, lwd=lwd, lend=lend)
}
plot(NA, xlim=c(-10,20), ylim=c(0,0.4), xlab="Mean", ylab="d(x)")
mapply(my_curve, seq(-5,5,5), c(1,3,5), rainbow(3))

Access lines plotted by R using basic plot()

I am trying to do the following:
plot a time series in R using a polygonal line
plot one or more horizontal lines superimposed
find the intersections of said line with the orizontal ones
I got this far:
set.seed(34398)
c1 <- as.ts(rbeta(25, 33, 12))
p <- plot(c1, type = 'l')
# set thresholds
thresholds <- c(0.7, 0.77)
I can find no way to access the segment line object plotted by R. I really really really would like to do this with base graphics, while realizing that probably there's a ggplot2 concoction out there that would work. Any idea?
abline(h=thresholds, lwd=1, lty=3, col="dark grey")
I will just do one threshold. You can loop through the list to get all of them.
First find the points, x, so that the curve crosses the threshold between x and x+1
shift = (c1 - 0.7)
Lower = which(shift[-1]*shift[-length(shift)] < 0)
Find the actual points of crossing, by finding the roots of Series - 0.7 and plot
shiftedF = approxfun(1:length(c1), c1-0.7)
Intersections = sapply(Lower, function(x) { uniroot(shiftedF, x:(x+1))$root })
points(Intersections, rep(0.7, length(Intersections)), pch=16, col="red")

I am plotting vectors in R in a 2-D cartestian system. My X and Y arrays are unequal in size, so how do I plot my X and Y vectors?

I am attempting to plot discrete functions in R for a flow model equation. I have to plot the original function u(x) = tanh(x - 0.1), with u(x) on the Y-axis and x on the X-axis. I then must plot a discrete function that describes the slope.
u <- array(0,dim=c(21))
#Plot the original function u(x)=tanh(ax-x0)
curve(tanh(x-0.1), from=0, to=5, n=100, col="red", xlab="x", ylab = "u(x)")
grid (NULL,NULL, col = "lightgray", lty="dotted")
x = seq(0, 5, by=0.25)
for (i in 1:21){
u[i] = tanh(x[i]-0.1)
}
x1 = seq(0, 4.75, by=0.25)
du1 <- array(0,dim=c(20))
for (i in 1:20){
du1[i] = (u[i+1]-u[i])/0.25
}
plot(x1, du1, xlab = "x", ylab = "du/dx")
So per the definition of my derivative function, my du/dx vector will only have 20 vector points, but my x vector still has 21 points. I must then repeat giving defined du/dx vectors that have 19 and 18 vector points. Is there any way I can plot the du/dx vs. x functions all on the same graph without having to redefine x every time?
I'm not sure I'm totally clear on what you're asking, but here's code that prevents you from writing out 18 individual code blocks (using the "diff" function in base).
derivs <- matrix(NA, nrow=21, ncol=18)
x <- seq(0, 5, by=0.25)
orig <- tanh(x-0.1)
derivs[,1] <- c(diff(orig)/.25, NA)
for(col in 2:18) {
print(col)
derivs[,col] <- c((diff(derivs[,col-1])/.25), NA)
}
The resulting matrix (here called "derivs" has a column for each derivative (first column is first derivative, second is second derivative, etc...)
One reason I'm a bit confused about what you're trying for is that, if you were to plot all these on one graph, it would be a really weird graph, because the order of magnitudes are really different between the first few, and the last few derivatives.
The dimensions aren't really different for each derivative; I've simply padded it with NAs, which won't appear on a graph.
Also note that you can use the diff function to get second-order differences and so forth.
PS. The graph will probably look more reasonable if, rather than taking the differences as you did (and as I did, to emulate you), so that the different is assigned to the first x value...you probably want to center. E.g. every other derivative would actually be plotted at .125, .375, etc.)

histogram and pdf in the same graph [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fitting a density curve to a histogram in R
I'd like to plot on the same graph the histogram and various pdf's. I've tried for just one pdf with the following code (adopted from code I've found in the web):
hist(data, freq = FALSE, col = "grey", breaks = "FD")
.x <- seq(0, 0.1, length.out=100)
curve(dnorm(.x, mean=a, sd=b), col = 2, add = TRUE)
It gives me an error. Can you advise me?
For multiple pdf's what's the trick?
And I've observed that the histogram seems to be plot the density (on y-y axis) instead of the number of observations.... how can I change this?
Many thanks!
It plots the density instead of the frequency because you specified freq=FALSE. It is not very fair to complain about it doing exactly what you told it to do.
The curve function expects an expression involving x (not .x) and it does not require you to precompute the x values. You probably want something like:
a <- 5
b <- 2
hist( rnorm(100, a, b), freq=FALSE )
curve( dnorm(x,a,b), add=TRUE )
To head of your next question, if you specify freq=TRUE (or just leave it out for the default) and add the curve then the curve just runs along the bottom (that is the whole purpose of plotting the histogram as a density rather than frequencies). You can work around this by scaling the expression given to curve by the width of the bins and the number of total points:
out <- hist( rnorm(100, a, b) )
curve( dnorm(x,a,b)*100*diff(out$breaks[1:2]), add=TRUE )
Though personally the first option (density scale) without tickmark labels on the y-axis makes more sense to me.
h<-hist(data, breaks="FD", col="red", xlab="xTitle", main="Normal pdf and histogram")
xfit<-seq(min(data),max(data),length=100)
x.norm<-rnorm(n=100000, mean=a, sd=b)
yfit<-dnorm(xfit,mean=mean(x.norm),sd=sd(x.norm))
yfit <- yfit*diff(h$mids[1:2])*length(loose_All)
lines(xfit, yfit, col="blue", lwd=2)

Resources