Plotting Contours with x, y, z values - r

I am trying to create a contour plot of 1000 data points. I have the matrix with all of the values in it. Here is my code.
mu1 <- rbind(2, 2)
mu2 <- rbind(-2, -2)
sigma1 <- rbind(c(.6, 0), c(0, .6))
simga2 <- sigma1
det1 <- det(sigma1)
det2 <- det1
inv1 <- solve(sigma1)
inv2 <- inv1
x <- runif(1000, -5, 5)
y <- runif(1000, -5, 5)
w <- rbind(x, y)
ratio <- function(v){
quotient <- (exp((-1/2)*t(v-mu1)%*%inv1%*%(v-mu1)))/(exp((-1/2)*t(v-mu2)%*%inv2%*%(v-mu2)))
return(quotient)
}
z <- apply(w, 2, ratio)
round.z <- round(z, digits=0)
df <- cbind(x, y, z, round.z)
df <- as.data.frame(df)
I want to plot the contours of x and y by the round.z values including where round.z=1. I know that the contour where round.z=1 should be the line y=-x, but I don't know how to get it to show up. Thanks for the help.

The contour and related functions in R want to have the data on a grid, not a random sample like yours. The akima::interp function can convert your data to this format. For example, after running your code,
library(akima)
grid <- with(df, interp(x, y, round.z))
contour(grid, levels = 10^(0:10))
which produces this image:

Related

Hist with lines in R

I generate 4 parts of big data: cluster1(10000 points), cluster2(15000 points), cluster3(15000 points) and throws(500 points). Here is the code:
library('MASS')
library('fpc')
#library("dbscan")
library("factoextra")
library("clustertend")
library("boot")
library("stream")
set.seed(123)
mu1<-c(-5,-7)
mu1
sigma1<-matrix(c(4,-2,-2,2), nrow=2, ncol=2, byrow = TRUE)
sigma1
n<-10000
cluster1<-mvrnorm(n,mu1,sigma1)
cluster1
#cluster1<-as.data.frame(cluster1)
#cluster1
#c<-runif(10000,1,1000)
#c
phi <- runif(15000, max = 2*pi)
rho <- sqrt(runif(15000))
x <- sqrt(5)*rho*cos(phi) + 6
y <- sqrt(10/3)*rho*sin(phi) + 4
range(2*(x - 6)^2 + 3*(y - 4)^2)
#[1] 0.001536582 9.999425234
plot(x, y)
cluster2<-cbind(x,y)
cluster2
u <- runif(15000, max = 3)
v <- runif(15000, max = 2)
x <- u + v - 10
y <- v - u + 8
range(x + y)
#[1] -1.999774 1.999826
range(x - y + 15)
#[1] -2.999646 2.999692
plot(x, y)
cluster3<-cbind(x,y)
cluster3
#cluster3<-as.data.frame(cluster1)
#cluster3
x <- runif(500, -20, 20)
y <- runif(500, -20, 20)
#u <- runif(500, max = 20)
#v <- runif(500, max = 20)
#x <- u + v - 20
#y <- v - u
range(x)
range(y)
plot(x,y)
throws<-cbind(x,y)
throws
data<-rbind(cluster1,cluster2,cluster3,throws)
data<-as.data.frame(data)
data
plot(data)
Then I try by using the bootstrap method, construct a distribution of H statistics for some
fixed m, which is from 7% of the total number of generated points(m=2835). Here is th code where I do this:
B<-10#number of iterations
H<-NULL#value of Hopkins statistic
for(i in 1:B){
N<-dim(data)[1]
s<-sample(N,0.8*N)
stat<-hopkins(data[s,], n=2835, byrow = TRUE)$H
H[i]<-stat
#print(c(i, stat))
}
It takes very to generate. Then I should to compare this result with beta distribution - B(m,m). Here is the code:
hist(H)
#(density(H), col="red")
#hist(distB)
X<-seq(min(H), max(H), 0.001)
X
lines(X, dbeta(X,2835,2835), type="l", col="red")
The problem is that lined doesn't draw on hist. Can anybody say what is the problem? Here is the image, I see red line, but it's not exactly right.
Your y-axis values plotted by dbeta() are way too low to register on the supplied y-axis (<0.0000001). You need to overlay the second plot:
# sample data
H <- sample(seq(0.455,0.475,0.001), 1000, replace = TRUE)
#plot histogram
hist(H)
# prepare graphics to add second plot
par(new = TRUE)
# sample data for second plot
X <- seq(0.455,0.475, 0.001)
Y <- dbeta(X,2835,2835)
# plot second plot, remove axes
plot(X, dbeta(X,2835,2835), type="l", col="red", axes = FALSE)
axis(4, Y) # add axis on right side

R Error: Coloring Graphs According to Values Within a Matrix

I am working with the R programming language.
I am trying to make a 3 Dimensional Graph between variables "x, y and w", and color this graph according to values of "z" :
library(plotly)
library(dplyr)
X <- seq(0,3.1,0.1)
Y <- seq(0,3.1,0.1)
W <- seq(0,3.1,0.1)
DF <- expand.grid(X,Y, W)
#Compute variable for colors
DF$Z <- sin(DF$Var1) + cos(DF$Var2) + sin(DF$Var3)
#make a matrix of color values
Mat <- matrix(DF$Z,nrow = 32)
#make a matrix for z values
Mat2 <- matrix(rep(c(1:16,16:1),32),nrow=32)
#plot
plot_ly(y=~Y,x=X, z=~W) %>%
add_surface(surfacecolor=~Mat)
But this produces an error:
Error: `z` must be a numeric matrix
Can anyone please show me how to fix this problem?
Thanks
Note: For some reason, the following code works:
X <- seq(0,3.1,0.1)
Y <- seq(0,3.1,0.1)
DF <- expand.grid(X,Y)
#Compute variable for colors
DF$Z <- sin(DF$Var1) + cos(DF$Var2)
#make a matrix of color values
Mat <- matrix(DF$Z,nrow = 32)
#make a matrix for z values
Mat2 <- matrix(rep(c(1:16,16:1),32),nrow=32)
plot_ly(y=~Y,x=X, z=~Mat2) %>%
add_surface(surfacecolor=~Mat)
Your data are essentially points on a line in three dimensions (X, Y, W) so it's not clear what surface you want to plot. add_surface expects z-values to be a 32x32 matrix (since X and Y have 32 entries each) but you supply the vector W in your (first) call, hence the error. In your second attempt, you supply Mat2 which is a matrix with appropriate dimensions. Also note that the surfacecolor needs to be 32x32 matrix, too.
So set up the W matrix, compute the color matrix colors (I use a matrix of ones for simplicity below),
W <- matrix(rep(1, 32^2), ncol = 32)
grid <- data.frame(W = c(W), X = rep(X, each = 32), Y = Y)
colors <-
matrix(
mapply(function(x,y,z) sin(x)+cos(y)+sin(z), grid$X, grid$Y, grid$W),
nrow = 32, byrow = T
)
and plot:
plot_ly(y = ~Y, x = ~X, z = ~W) %>%
add_surface(surfacecolor = ~colors)
Edit
To plot X, Y, and Z, suitably transform DF$Z to a 32x32 matrix:
DF <- expand.grid(X,Y)
DF$Z <- sin(DF$Var1) + cos(DF$Var2)
Z <- matrix(DF$Z, nrow = 32)
plot_ly(y = ~Y, x = ~X, z=~Z) %>%
add_surface()

How to get R contour function to plot decimals

I am trying to plot the contours of a function made of two gaussians, one centered at (2, 2) and the other centered at (-2, -2). Here is my code.
k1 <- 2
k2 <- 2
mu1 <- rbind(2, 2)
mu2 <- rbind(-2, -2)
sigma1 <- rbind(c(.6, 0), c(0, .6))
sigma2 <- rbind(c(.3, 0), c(0, .3))
det1 <- det(sigma1)
det2 <- det(sigma2)
inv1 <- solve(sigma1)
inv2 <- solve(sigma2)
x <- runif(1000, -5, 5)
y <- runif(1000, -5, 5)
w <- rbind(x, y)
ratio <- function(v){
quotient <- log((2*pi)^(-k1/2)*det1^(-1/2)*(exp((-1/2)*t(v-mu1)%*%inv1%*%(v-mu1))))/log((2*pi)^(-k2/2)*det2^(-1/2)*(exp((-1/2)*t(v-mu2)%*%inv2%*%(v-mu2))))
return(quotient)
}
z <- apply(w, 2, ratio)
round.z <- round(z, digits=0)
df <- cbind(x, y, z, round.z)
df <- as.data.frame(df)
grid <- with(df, interp(x, y, z))
contour(grid, levels=0:10, asp=1)
But when I plot these contours I just get the contours with whole number values. It looks like this:
There should be more, similar-looking contours in the first quadrants that have decimal values (because I am taking a ratio) but they do not appear. I can't seem to find how to get contour() to plot decimals. Anyone know how to fix this problem?
As user2554330 commented, I can use levels=c((0:10)/10, 2:10). Thank you to them!

How to show matrix values on Levelplot

I have a matrix data here, and I visualized it with levelplot. The Plot is placed below. But I just couldn't put the values into the plot, I mean I read this question, but still couldn't figure it out.
How can I do that ? Thanks.
The problem with the code in the answer you linked to is that it only works when the objects in the levelplot's formula are named x, y, and z.
Here is an example that uses a more standard idiom for processing the arguments passed in to the custom panel function and so becomes more generally applicable:
library("lattice")
## Example data
x <- seq(pi/4, 5*pi, length.out=10)
y <- seq(pi/4, 5*pi, length.out=10)
grid <- expand.grid(X=x, Y=y)
grid$Z <- runif(100, -1, 1)
## Write a panel function (after examining 'args(panel.levelplot) to see what
## will be being passed on to the panel function by levelplot())
myPanel <- function(x, y, z, ...) {
panel.levelplot(x,y,z,...)
panel.text(x, y, round(z,1))
}
## Try it out
levelplot(Z ~ X*Y, grid, panel = myPanel)
mat <- read.csv("J_H2S1T6_PassTraffic.csv", header=F)
y <- as.numeric(mat[1,-1])
mat <- mat[-1,-1]
n <- dim(mat)[1]
Here a modification, I generate a new scale
x <- seq(min(y), max(y), length.out=n)
grid <- expand.grid(x=x, y=x)
mat <- as.matrix(mat)
dim(mat) <- c(n*n,1)
grid$z <- mat
Here the modification. I change the dimension of the matrix to a vector to put it in the grid .
mat <- as.matrix(mat)
dim(mat) <- c(n*n,1)
grid$z <- mat
p <- levelplot(z~x*y, grid,
panel=function(...) {
arg <- list(...)
panel.levelplot(...)
panel.text(arg$x, arg$y,arg$z)},
scales = list(y = list(at=y,labels=y),
x = list(at=y,labels=y)))
print(p)
Another option is to use layer() from latticeExtra. It allows you to overlay one plot on top of another, using the + operator familiar to ggplot2 enthusiasts:
library(latticeExtra)
## Applied to the example data in my other answer, this will produce
## an identical plot
levelplot(Z ~ X*Y, data = grid) +
layer(panel.text(X, Y, round(Z, 1)), data = grid)

Using dates on axis in persp

I'm trying to plot the dates on the x-axis of a persp plot, but cannot find a way of doing so. This is where I am at:
x <- seq(-10, 10, length= 30)
x0 <- as.Date("2000-01-01")
x.dates <- seq(x0,x0+length(x)-1,1)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
op <- par(bg = "white")
persp(x.dates, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",ticktype="detailed")
Here's a way to plot perspective with dates (by Jeff Ryan):
http://www.quantmod.com/examples/chartSeries3d/
The alpha code for the above graph is at the following url. This is a DOWNLOAD of R code, so I purposely omitted the http stuff:
www.quantmod.com/examples/chartSeries3d/chartSeries3d.alpha.R
If you look at the code, you can see how he did it.

Resources