levelplot - how to use it, any simple examples? - r

I woud like to understand how levelplot works. I have almost no experience with plots and R.
What confuses me, is how should I interpret for example x~y*z ?
Lets assume I have a function, and I would like to show how often certain value occurs by using 3d plot. I would have hence x = x, y = f(x) and z = count. How to obtain such simple plot by using levelplot (or something else if it is not appriopriate).
In addition, should I group "count" myself - 3 columns in my data from, or just have 2 columns - x and f(x) and have duplications?
Hope my question is clear, I tried to read levelplot documentation, however I could not find any tutorial that teaches basics.

The following example is from the ?levelplot documentation.
The formula z~x*y means that z is a function of x, y and the interaction between x and y. Had the function been z~x+y it would have meant that z is a function of x and y, ignoring any interaction.
You can read more about the formula interface in the help for ?formula.
x <- seq(pi/4, 5 * pi, length.out = 100)
y <- seq(pi/4, 5 * pi, length.out = 100)
r <- as.vector(sqrt(outer(x^2, y^2, "+")))
grid <- expand.grid(x=x, y=y)
grid$z <- cos(r^2) * exp(-r/(pi^3))
levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="",
ylab="", main="Weird Function", sub="with log scales",
colorkey = FALSE, region = TRUE)

Related

How to draw the sum of two CDF in R

I try to plot a linear combination of the CDF of standard normal distribution 1-Phi(2-x)+Phi(-2-x), where Phi is the CDF of standard normal distribution. I know how to draw one, such as Phi(2-x) and I also put the code as below. But how to draw the sum of two CDF in R or Python?
My code is
m <- 0
s <- 1
z <- pnorm(x,mean=m,sd=s)
plot(2-x, z,type="l",col="blue",lwd=2,las=1, xlab="X")
curve(-pnorm(2 - x) + pnorm(-2 - x), from = -10, to = 10)
pnorm is the cumulative distribution function. You can use + for addition, just like normal. At the ?pnorm help page you can see that the defaults are mean = 0 and sd = 1, so you don't need to specify them.
curve is a handy shortcut, but you could do a little bit more work to use plot as you did in the question:
n = 500
x = seq(-5, 5, length.out = n)
plot(x, -pnorm(2 - x) + pnorm(-2 - x),
type="l",col="blue",lwd=2,las=1, xlab="X")

How do I make x and y axes thicker with Plots (Julia)?

How can I make the lines for the x- and y-axes thicker in Julia Plots?
Is there a simple way to achieve this?
MWE:
using Plots
Nx, Ny = 101,101
x = LinRange(0, 100, Nx)
y = LinRange(0, 100, Ny)
foo(x,y; x0=50, y0=50, sigma =1) = exp(- ((x-x0)^2 + (y-y0)^2)/(2*sigma^2) )
NA = [CartesianIndex()] # for "newaxis"
Z = foo.(x[:,NA], y[NA,:], sigma=10);
hm = heatmap(x, y, Z, xlabel="x", ylabel="y", c=cgrad(:Blues_9), clim=(0,1))
plot(hm, tickfontsize=10, labelfontsize=14)
Leads to:
The posts I found so far suggested that this was not possible:
https://discourse.julialang.org/t/plots-jl-modify-frame-thickness/24258/4
https://github.com/JuliaPlots/Plots.jl/issues/1099
It this still so?
The actual code for my plot is much longer.
I would not like to rewrite all of it in a different plot library.
Currently, there does not seem to be an attribute for axes thickness in Plots.jl.
As a workaround, you may use the attribute thickness_scaling, which will scale the thickness of everything: lines, grid lines, axes lines, etc. Since you only want to change the thickness of axes, you need to scale down the others. Here is your example code doing that using pyplot backend.
using Plots
pyplot() # use pyplot backend
Nx, Ny = 101,101
x = LinRange(0, 100, Nx)
y = LinRange(0, 100, Ny)
foo(x,y; x0=50, y0=50, sigma =1) = exp(- ((x-x0)^2 + (y-y0)^2)/(2*sigma^2) )
NA = [CartesianIndex()] # for "newaxis"
Z = foo.(x[:,NA], y[NA,:], sigma=10);
hm = heatmap(x, y, Z, xlabel="x", ylabel="y", c=cgrad(:Blues_9), clim=(0,1))
plot(hm, tickfontsize=10, labelfontsize=14) # your previous plot
# here is the plot code that shows the same plot with thicker axes on a new window
# note that GR backend does not support `colorbar_tickfontsize` attribute
plot(hm, thickness_scaling=2, tickfontsize=10/2, labelfontsize=14/2, colorbar_tickfontsize=8/2, reuse=false)
See Julia Plots Documentation for more about plot attributes.
A simple workaround where you do not need to add attributes for all the fonts is to add verticle and horizontal lines at the limits for x and y of the plots. For example, if I have a figure fig with 4 subplots, each with the same bounds, I can use this to get a thicker box frame:
for i ∈ 1:4
vline!(fig[i], [xlim_lb, xlim_ub],
linewidth=3,
color=:black,
label=false)
hline!(fig[i], [ylim_lb, ylim_ub],
linewidth=3,
color=:black,
label=false)
end
or for the original example here, add this to the end:
frame_thickness = 5
vline!([x[1], x[end]], color=:black, linewidth=frame_thickness, label=false)
hline!([y[1], y[end]], color=:black, linewidth=frame_thickness, label=false)

R Statistics Distributions Plotting

I am having some trouble with a homework I have at Statistics.
I am required to graphical represent the density and the distribution function in two inline plots for a set of parameters at my choice ( there must be minimum 4 ) for Student, Fisher and ChiS repartitions.
Let's take only the example of Student Repartition.
From what I have searched on the internet, I have come with this:
First, I need to generate some random values.
x <- rnorm( 20, 0, 1 )
Question 1: I need to generate 4 of this?
Then I have to plot these values with:
plot(dt( x, df = 1))
plot(pt( x, df = 1))
But, how to do this for four set of parameters? They should be represented in the same plot.
Is this the good approach to what I came so far?
Please, tell me if I'm wrong.
To plot several densities of a certain distribution, you have to first have a support vector, in this case x below.
Then compute the values of the densities with the parameters of your choice.
Then plot them.
In the code that follows, I will plot 4 Sudent-t pdf's, with degrees of freedom 1 to 4.
x <- seq(-5, 5, by = 0.01) # The support vector
y <- sapply(1:4, function(d) dt(x, df = d))
# Open an empty plot first
plot(1, type = "n", xlim = c(-5, 5), ylim = c(0, 0.5))
for(i in 1:4){
lines(x, y[, i], col = i)
}
Then you can make the graph prettier, by adding a main title, changing the axis titles, etc.
If you want other distributions, such as the F or Chi-squared, you will use x strictly positive, for instance x <- seq(0.0001, 10, by = 0.01).

Why I can change the x axis? R

I tried to run the following script to change the x axis. I followed other answers given in Stack Overflow; however I don’t get what I’m looking for. The original x axis goes from 0 to 1 but I want to change it from 0 to 20.
x<-c(0,0.1,0.2,0.25,0.30,0.35,0.40,0.60,0.90,1)
y<-c(0,0.014,0.41165,0.258,0.57,0.57,0.1803,0.5844,0.10185,0.085)
da<-cbind(x,y)
dat=data.frame(da)
plot(y~x,data=dat,xaxt="n")
pas=c(0,1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20)
axis(1, at=1:20,labels=pas)
This script produces a figure with just a 0 at the last mark. I need a x axis from 0 to 20. Thanks
I am not sure why you are trying to do this but the following would work.
x <- c(0,0.1,0.2,0.25,0.30,0.35,0.40,0.60,0.90,1)
y <- c(0,0.014,0.41165,0.258,0.57,0.57,0.1803,0.5844,0.10185,0.085)
dat <- data.frame(x = x, y = y)
x.range <- c(0,20)
x.labels <- x.range[1]:x.range[2]
pas <- seq(0, 1, length.out = length(x.labels))
plot(y ~ x, data = dat, xaxt = "n", xlim = c(0,1))
axis(1, at = pas, labels = x.labels, cex.axis=0.65)
You may have missed the xlim/ylim.
Did you mean y axis? Then just use :
plot(y~x,data=dat,ylim=c(0,20))
plot(y~x,data=dat,xlim=c(0,20))# you need to remove the 'xaxt="n"' to see the x-axis
Although either way I am not sure this is the best idea given the range of the data.
Using ggplot2
library(ggplot2)
qplot(x,y,data=dat)+ scale_x_continuous(labels=c("0"="fake0","0.25"="fake5","0.5"="fake10",".75"="fake15","1"="fake20"))# replace 'fake#' with anything
Although I am not sure why are you trying to do this.

Drawing an interval on the graph using vertical line in R ?

install.packages("devtools")
library(devtools)
devtools::install_github("google/CausalImpact")
library(CausalImpact)
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)
pre.period <- c(1, 70)
post.period <- c(71, 100)
impact <- CausalImpact(data, pre.period, post.period)
plot(impact, "cumulative")
Say i want the graph to show an interval from 71-100 with the x scales starting at 1 from the first dotted line any ideas on how to do this?
Does anyone have any idea how to add a second vertical dotted line depicting an interval on the graph? Thanks.
You can use abline() to add lines to a graph, with the argument v = 70 setting a vertical line at x = 70. I'm not sure how to restart the x-scale from that point however - it doesn't seem like something that would be possible but perhaps someone else knows how.
You can reset the axes using this.
In your initial plot command, set xaxt = "n" This ensures that the plot function does not mark the axes.
You can then draw the abline(v=70) as mentioned above.
Then use axis(1,at=seq(60,80,by=1),las=1) 1 stands for x-axis and in the at attribute, mention the x limits you want. I've put in 60 to 80 as an example.

Resources