Plot a generic surface and contour in R -
i have following data
var.asym <- function(alpha1, alpha2, xi, beta, n){ term11 <- alpha1*(1-alpha1)^(2*xi-1) term12 <- alpha1*(1-alpha1)^(xi-1)*(1-alpha2)^xi term22 <- alpha2*(1-alpha2)^(2*xi-1) sigma <- matrix(c(term11, term12, term12, term22), nrow=2, byrow=true) sigma*beta^2/n } mop.jacob.inv <- function(alpha1, alpha2, xi, beta){ term11 <- -qgpd(alpha1, xi, 0, beta)/xi - beta*(1-alpha1)^xi*log(1-alpha1)/xi term12 <- qgpd(alpha1, xi, 0, beta)/beta term21 <- -qgpd(alpha2, xi, 0, beta)/xi - beta*(1-alpha2)^xi*log(1-alpha2)/xi term22 <- qgpd(alpha2, xi, 0, beta)/beta jacob <- matrix(c(term11, term12, term21, term22), nrow=2, byrow=true) jacob.inv <- solve(jacob) jacob.inv } var.asym2 <- function(alpha1, alpha2) var.asym(alpha1, alpha2, 0.2, 1, 1000) mop.jacob.inv2 <- function(alpha1, alpha2) mop.jacob.inv(alpha1, alpha2, 0.2, 1) object <- function(alpha1, alpha2){ term1 <- mop.jacob.inv2(alpha1, alpha2)%*%var.asym2(alpha1, alpha2)%*%t(mop.jacob.inv2(alpha1, alpha2)) sum(diag(term1)) } x <- seq(0.01, 0.98, by=0.01) y <- seq(x[1]+0.01, 0.99, by=0.01) xy <- cbind(rep(x[1], length(x)), y) for(i in 2:length(x)){ y <- seq(x[i]+0.01, 0.99, by=0.01) xy <- rbind(xy, cbind(rep(x[i], length(x)-i+1), y)) } object.xy <- rep(0, 4851) for(i in 1:4851){ object.xy[i] <- object(xy[i, 1], xy[i, 2]) }
now want plot surface of (xy[, 1], xy[, 2], object.xy)
. there way in r
? tried persp
, contour
function did not seem appropriate case since both require increasing sequences x , y. i guess more general question how make contour plot when given sequence of triplets (x, y, z).
library(dplyr) library(tidyr) library(magrittr) long_data = data.frame( x = xy[,1] %>% round(2), y = xy[,2] %>% round(2), z = object.xy) wide_data = long_data %>% spread(x, z) y = wide_data$y wide_data %<>% select(-y) x = names(wide_data) %>% as.numeric z = wide_data %>% as.matrix persp(x, y, z) contour(x, y, z)
dunno why round helps, does. reshape necessary build matrix x, y, z data. note contour lines coalesce black dot because of huge narrow peak in data.
Comments
Post a Comment