curve add=TRUE but drawing independent graphincs - r

In statistics, there is rejection method to generate a random variable.
(but it is not main problem)
I finished the sampling, and want to draw graphics in one screen.
I thought it was an 'add=TRUE' option, and I set it up.
But it showed me a new screen.
I do not know what is wrong.
I'm sorry to post a trivial question, but I have no other place to ask.
nsample=10000
fx = function(x){2*exp(-(x^2)/2)/sqrt(2*pi)}
gx = function(x){exp(-x)}
fxdivgx = function(x){(2*exp(-(x^2)/2)/sqrt(2*pi)/exp(-x))}
grid=seq(0.0,5.0, length.out =1000)
which(fxdivgx(grid)==max(fxdivgx(grid)))
grid[201] #x valuable which fx/gx has maximum value
const = fxdivgx(grid[201])
const
fn = function(x){((2*exp(-(x^2)/2)/sqrt(2*pi))/(exp(-x)*const))}
result2 = list()
result2$candi=rexp(nsample)
result2$targetDen=fn(result2$candi)
result2$keep=ifelse(runif(nsample)<result2$targetDen, TRUE, FALSE)
hist(result2$candi[result2$keep], freq=F, breaks=100)
curve(2*exp(-(x^2)/2)/sqrt(2*pi), add='TRUE', col='red')
This is my code.
When I run this code, the results are printed on different screens.
How do I print two pictures in one screen?
hist(result$candi[result$keep], breaks=100)
curve((2*exp(-(x^2)/2)/sqrt(2*pi)), add=TRUE, col='red')
after plotting these two lines, i got below graphics.

Related

Errors in R Histogram

Can anyone understand why this block of code isn't producing a histogram? Here is the code:
incremental <- c()
for (i in 1:1000) {
set.seed(42)
avg_2 = mean(runif(100))
incremental <- rbind(incremental, c(avg_2))
}
incremental <- as.numeric(incremental)
hist(incremental, main = "Histogram of Averages From For Loop",
xlab = "Averages")
Don't worry about the set.seed, it is part of the exercise. All the data points will be the same, but nothing shows up on the histogram. Why is this so? Here is a screenshot of the histogram:
Actually, you are just looking at a plot with one big bar. It's very hard for R (or anyone) to guess where to create breaks if you only observe one value. Maybe you want something like this:
hist(incremental, main = "Histogram of Averages From For Loop",
xlab = "Averages",
breaks=seq(0,1, length.out=10))
This tells hist() to create 10 breaks in the range from 0 to 1.

Interactive plot: Manipulate contents of a ggplot2 plot with a sliding bar

Edit: Thank you to Javier for his suggestion. I forgot to mention that I would like to incorporate this interactive plot into a report / dashboard, so something that works with a HTML document from RMarkdown would be ideal, but a dashboard solution would also be fine.
Consider the following plots; the red line represents the actual data, while the green line plots predictions generated by a model:
The predictions of two different models are displayed; one trained over the first 100 hours, and the other over the first 216 hours. Predictions are then generated for the unseen data-points, then plotted.
What I would like to do, is train n models, eg. one every 12 hours in an expanding window fashion. After having done this, I would like to present the results in an interactive fashion where the user can click/slide something to move the vertical line back and forth, thereby changing which model's predictions are displayed. The point would be to intuitively show the effect of different training lengths.
I'm new to shiny and interactive plots in R; can this be done without too much trouble?
You can with the manipulate package for quick interactive plots. Shiny requires more fine-tuning and it is more time-consuming.
Here is a reproducible example for you to test out:
This creates the slider bar:
library(manipulate)
manipulate(plot(1:x), x = slider(1, 100))
Put your code here for the creation of the interactive plot:
manipulate(
plot(cars, xlim = c(0, x.max), type = type, ann = label),
x.max = slider(10, 25, step=5, initial = 25),
type = picker("Points" = "p", "Line" = "l", "Step" = "s"),
label = checkbox(TRUE, "Draw Labels"))
Check out the CRAN manipulate package for more information:
https://cran.r-project.org/web/packages/manipulate/index.html
I was able to do this with the example at the bottom of this link.
library(shiny)
sliderInput("n", "Training length:", 100, min=24, max= 11*24)
renderPlot({
plotPredictCurve(data= df, trainLength= input$n)
})

Using panel.mathdensity and panel.densityplot in lattice graphics to plot Bayesian prior and posterior

I am trying to plot a Bayesian prior and posterior distribution using lattice graphics. I would like to have both distributions in one panel, for direct comparison.
I've tried different solutions all day, including qqmath but I didn't get them to work. Here's the attempt that has been most successful so far:
# my data
d <- dgamma(seq(from=0.00001,to=0.01,by=0.00001),shape = .1, scale = .01)
# my plot
densityplot(~d,
plot.points=FALSE,
panel = function(x,...) {
panel.densityplot(x,...)
panel.mathdensity(
dmath = dgamma,
args = list(shape = .1, scale=.01)
)
}
)
Even though the code runs through nicely, it doesn't do what I want it to. It plots the posterior (d) but not the prior.
I added stop("foo") to densityplot(...) to stop execution if an error occurs and I searched online for the error message:
Error in eval(substitute(groups), data, environment(formula)) : foo
But there are only a few results and they seem unrelated to me.
So, here's my question: Can anyone help me with this approach to achieve what I want?
I asked a similar question which leads to the same result. I got an answer and it was useful. You can find everything here

What does negative length vectors in a wireframe plot (lattice package) means?

I want to plot a wireframe in R using the lattice package. However, I get the following error message "error using packet 1 negative length vectors are not allowed". The data looks like the following:
> result_mean
experiment alpha beta packet
1 0 1.0 1 3.000000
2 0 1.1 1 2.571429
The command to create the data is the following
png(file=paste("foobar.png"),width=1280, height=1280);
plot <- wireframe(result_mean$packet ~ result_mean$alpha * result_mean$beta,
data=result_mean, scales = list(arrows=FALSE, cex= .45, col = "black", font = 3),
drape = TRUE, colorkey = TRUE, main = "Foo",
col.regions = terrain.colors(100),
screen = list(z = -60, x = -60),
xlab="alpha", ylab="beta", zlab="mean \npackets");
print(plot);
dev.off();
I'm wondering what this error message means and if there is a good way to debug this?
Thanks in advance!
Debugging lattice graphics is a bit difficult because (a) the code is complex and multi-layered and (b) the errors get trapped in a way that makes them hard to intercept. However, you can at least get some way in diagnosing the problem.
First create a minimal example. I suspected that your problem was that your data fall on a single line, so I created data that looked like that:
d <- data.frame(x=c(1,1.1),
y=c(1,1),
z=c(2,3))
library(lattice)
wireframe(z~y*x,data=d)
Now confirm that fully three-dimensional data (data that define a plane) work just fine:
d2 <- data.frame(expand.grid(x=c(1,1.1),
y=c(1,1.1)),
z=1:4)
wireframe(z~y*x,data=d2)
So the question is really -- did you intend to draw a wireframe of two points lying on a line? If so, what did you want to have appear in the plot? You could hack things a little bit to set the y values to differ by a tiny bit -- I tried it, though, and got no wireframe appearing (but no error either).
edit: I did a bit more tracing, with various debug() incantations (and searching the source code of the lattice package and R itself for "negative length") to deduce the following: within a function called lattice:::panel.3dwire, there is a call to a C function wireframePanelCalculations, which you can see at https://r-forge.r-project.org/scm/viewvc.php/pkg/src/threeDplot.c?view=markup&root=lattice
Within this function:
nh = (nx-1) * (ny-1) * ng; /* number of quadrilaterals */
sHeights = PROTECT(allocVector(REALSXP, nh));
In this case nx is zero, so this code is asking R to allocate a negative-length vector, which is where the error comes from.
In this case, though, I think the diagnosis is more useful than the explicit debugging.

Producing a data.frame for presence/absence for each raster cell in R

G'day,
I have a data set I am trying to run a boosted regression tree model on with code:
pa.brt.m <- gbm.step(data=data, gbm.x = 5:15, gbm.y = 2,
family = "bernoulli", tree.complexity = 5,
learning.rate = 0.01, bag.fraction = 0.5)
As it goes about it's business, it returns the error:
Error in plot.new() : figure margins too large
I am wondering what is going on and how I can fix this? This error seems to stop the function and I don't get the rest of the output I would expect. Can anyone provide some insight into what is going on?
This happens when the plotting area
is too small to put the margins
(margins have an absolute dimension:
they will not shrink),
especially when you want many small
plots.
If you had issued a command such as par(mfrow=c(100,100)),
you need to undo it, e.g., by closing the plot window.
This is the most probable cause of the problem.
You can also try to enlarge ("maximize") the plot window.
You can also try to change the margins, e.g. with
par(mar=c(0,0,0,0),oma=c(0,0,0,0)).
You can also try to divert the plot to a file,
with sufficiently large dimensions.
pdf("a.pdf", width=100, height=100)
...
dev.off()

Resources