Changing the scales in a wireframe () - r

In the following 3D plot I want my 'percentile' axis and 'phi' axis to be scaled from 0 to 1 instead of 0 to 10. I would appreciate it if anyone could help me with this:
x1<-c(13,27,41,55,69,83,97,111,125,139)
x2<-c(27,55,83,111,139,166,194,222,250,278)
x3<-c(41,83,125,166,208,250,292,333,375,417)
x4<-c(55,111,166,222,278,333,389,445,500,556)
x5<-c(69,139,208,278,347,417,487,556,626,695)
x6<-c(83,166,250,333,417,500,584,667,751,834)
x7<-c(97,194,292,389,487,584,681,779,876,974)
x8<-c(111,222,333,445,556,667,779,890,1001,1113)
x9<-c(125,250,375,500,626,751,876,1001,1127,1252)
x10<-c(139,278,417,556,695,834,974,1113,1252,1391)
df<-data.frame(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)
df.matrix<-as.matrix(df)
library(lattice)
wireframe(df.matrix,
aspect = c(61/87, 0.4),scales=list(arrows=FALSE,cex=.5,tick.number="10",z=list(arrows=T)),ylim=c(1:10),xlab=expression(phi1),ylab="Percentile",zlab=" Loss",main="Random Classifier",
light.source = c(10,10,10),drape=T,col.regions = rainbow(100, s = 1, v = 1, start = 0, end = max(1,100 - 1)/100, alpha = 1),screen=list(z=-60,x=-60))

I tried this (following this post):
x <- data.frame(z = as.vector(df.matrix))
x$x <- rep(seq(0, 1, length.out = 10), 10)
x$y <- rep(seq(0, 1, length.out = 10), 10)
wireframe(z ~ x * y, x,
aspect = c(61/87, 0.4),
scales = list(arrows=FALSE,cex=.5,tick.number = 10, z = list(arrows=T)),
# ylim = 1:10,
xlab=expression(phi1),
ylab="Percentile",zlab=" Loss",main="Random Classifier",
light.source = c(10,10,10), drape=T,
col.regions = rainbow(100, s = 1, v = 1, start = 0, end = max(1,100 - 1)/100, alpha = 1),
screen=list(z=-60,x=-60))

Related

Drawing a partially transparent density polygon

How can I make this red polygon partially transparent so I can see the points underneath it?
library(ks)
set.seed(1234)
x <- runif(1000) + -150
y <- runif(1000) + 20
my.data <- data.frame(x,y)
my.matrix <- as.matrix(my.data)
my_gps_hpi <- Hpi(x = my.matrix, pilot = "samse", pre = "scale")
my.fhat <- kde(x = my.matrix, compute.cont = TRUE, h = my_gps_hpi,
xmin = c(min(my.data$x), min(my.data$y)),
xmax = c(max(my.data$x), max(my.data$y)),
bgridsize = c(100, 100))
my.contours <- c(75)
contourLevels(my.fhat, cont = my.contours)
contourSizes(my.fhat, cont = my.contours, approx = TRUE)
plot(my.data$x, my.data$y)
plot(my.fhat, lwd = 3, display = "filled.contour", cont = my.contours, add = TRUE)
png(file="transparent_polygon_June21_2021.png")
plot(my.data$x, my.data$y)
plot(my.fhat, lwd = 3, display = "filled.contour", cont = my.contours, add = TRUE)
dev.off()
I think I have figured out a solution by digging around in the source code in the file kde.R.
I made several changes to my code.
Changed my.fhat to fhat because the source code might want fhat.
Changed my.contours to contours for the same reason.
Changed contourLevels(my.fhat, cont = my.contours) to hts <- contourLevels(fhat, cont = contours) for the same reason.
Extracted the col.fun from the source code and changed it to return the color of my choice: col.fun <- function(n) {rgb(255, 0, 0, 127, maxColorValue=255)}.
Modified the plot statement to that shown in the code below.
Here is the modified R code:
setwd('C:/Users/mark_/Documents/ctmm/density_in_R/')
set.seed(1234)
library(ks)
x <- runif(1000) + -150
y <- runif(1000) + 20
my.data <- data.frame(x,y)
my.matrix <- as.matrix(my.data)
gps_hpi <- Hpi(x = my.matrix, pilot = "samse", pre = "scale")
fhat <- kde(x = my.matrix, compute.cont = TRUE, h = gps_hpi,
xmin = c(min(my.data$x), min(my.data$y)),
xmax = c(max(my.data$x), max(my.data$y)),
bgridsize = c(100, 100))
contours <- c(75)
hts <- contourLevels(fhat, cont = contours)
contourSizes(fhat, cont = contours, approx = TRUE)
col.fun <- function(n) {rgb(255, 0, 0, 127, maxColorValue=255)}
col.fun(1)
plot(fhat, lwd = 3, display = "filled.contour", cont = contours, col.fun = col.fun(1), drawpoints=TRUE)
png(file="transparent_polygon_June22_2021.png")
plot(fhat, lwd = 3, display = "filled.contour", cont = contours, col.fun = col.fun(1), drawpoints=TRUE)
dev.off()

Margin for alluvial plot

I use this example
library(alluvial)
tit <- as.data.frame(Titanic)
# only two variables: class and survival status
tit2d <- aggregate( Freq ~ Class + Survived, data=tit, sum)
alluvial( tit2d[,1:2], freq=tit2d$Freq, xw=0.0, alpha=0.8,
gap.width=0.1, col= "steelblue", border="white",
layer = tit2d$Survived != "Yes" , cex.axis =8)
Pay attention I use cex.axis =8 and i get
Axis labels go beyond
I try to use par(mar=c(10, 10, 10, 10)) but no result
thanks for any idea
There is a bug in the source code of the alluvial function
The function sets par(mar=c(2,1,1,1)) hard coded so using the par() outside doesn't have any effect.
You could change locally the source code of the function to one of 2 options:
add an argument mar_ and pass the margin, and set at the right place par(mar=mar_).
just overwrite locally the line to the desired margins
I found the first option more appealing because you can then set the values from outside the function and optimise more easily.
The source code:
function (..., freq, col = "gray", border = 0, layer, hide = FALSE,
alpha = 0.5, gap.width = 0.05, xw = 0.1, cw = 0.1, blocks = TRUE,
ordering = NULL, axis_labels = NULL, cex = par("cex"), cex.axis = par("cex.axis"))
{
p <- data.frame(..., freq = freq, col, alpha, border, hide,
stringsAsFactors = FALSE)
np <- ncol(p) - 5
if (!is.null(ordering)) {
stopifnot(is.list(ordering))
if (length(ordering) != np)
stop("'ordering' argument should have ", np, " components, has ",
length(ordering))
}
n <- nrow(p)
if (missing(layer)) {
layer <- 1:n
}
p$layer <- layer
d <- p[, 1:np, drop = FALSE]
p <- p[, -c(1:np), drop = FALSE]
p$freq <- with(p, freq/sum(freq))
col <- col2rgb(p$col, alpha = TRUE)
if (!identical(alpha, FALSE)) {
col["alpha", ] <- p$alpha * 256
}
p$col <- apply(col, 2, function(x) do.call(rgb, c(as.list(x),
maxColorValue = 256)))
isch <- sapply(d, is.character)
d[isch] <- lapply(d[isch], as.factor)
if (length(blocks) == 1) {
blocks <- if (!is.na(as.logical(blocks))) {
rep(blocks, np)
}
else if (blocks == "bookends") {
c(TRUE, rep(FALSE, np - 2), TRUE)
}
}
if (is.null(axis_labels)) {
axis_labels <- names(d)
}
else {
if (length(axis_labels) != ncol(d))
stop("`axis_labels` should have length ", names(d),
", has ", length(axis_labels))
}
getp <- function(i, d, f, w = gap.width) {
a <- c(i, (1:ncol(d))[-i])
if (is.null(ordering[[i]])) {
o <- do.call(order, d[a])
}
else {
d2 <- d
d2[1] <- ordering[[i]]
o <- do.call(order, d2[a])
}
x <- c(0, cumsum(f[o])) * (1 - w)
x <- cbind(x[-length(x)], x[-1])
gap <- cumsum(c(0L, diff(as.numeric(d[o, i])) != 0))
mx <- max(gap)
if (mx == 0)
mx <- 1
gap <- gap/mx * w
(x + gap)[order(o), ]
}
dd <- lapply(seq_along(d), getp, d = d, f = p$freq)
rval <- list(endpoints = dd)
===============================================
===============Need to edit====================
op <- par(mar = c(2, 1, 1, 1))
===============================================
plot(NULL, type = "n", xlim = c(1 - cw, np + cw), ylim = c(0,
1), xaxt = "n", yaxt = "n", xaxs = "i", yaxs = "i", xlab = "",
ylab = "", frame = FALSE)
ind <- which(!p$hide)[rev(order(p[!p$hide, ]$layer))]
for (i in ind) {
for (j in 1:(np - 1)) {
xspline(c(j, j, j + xw, j + 1 - xw, j + 1, j + 1,
j + 1 - xw, j + xw, j) + rep(c(cw, -cw, cw),
c(3, 4, 2)), c(dd[[j]][i, c(1, 2, 2)], rev(dd[[j +
1]][i, c(1, 1, 2, 2)]), dd[[j]][i, c(1, 1)]),
shape = c(0, 0, 1, 1, 0, 0, 1, 1, 0, 0), open = FALSE,
col = p$col[i], border = p$border[i])
}
}
for (j in seq_along(dd)) {
ax <- lapply(split(dd[[j]], d[, j]), range)
if (blocks[j]) {
for (k in seq_along(ax)) {
rect(j - cw, ax[[k]][1], j + cw, ax[[k]][2])
}
}
else {
for (i in ind) {
x <- j + c(-1, 1) * cw
y <- t(dd[[j]][c(i, i), ])
w <- xw * (x[2] - x[1])
xspline(x = c(x[1], x[1], x[1] + w, x[2] - w,
x[2], x[2], x[2] - w, x[1] + w, x[1]), y = c(y[c(1,
2, 2), 1], y[c(2, 2, 1, 1), 2], y[c(1, 1),
1]), shape = c(0, 0, 1, 1, 0, 0, 1, 1, 0, 0),
open = FALSE, col = p$col[i], border = p$border[i])
}
}
for (k in seq_along(ax)) {
text(j, mean(ax[[k]]), labels = names(ax)[k], cex = cex)
}
}
axis(1, at = rep(c(-cw, cw), ncol(d)) + rep(seq_along(d),
each = 2), line = 0.5, col = "white", col.ticks = "black",
labels = FALSE)
axis(1, at = seq_along(d), tick = FALSE, labels = axis_labels,
cex.axis = cex.axis)
par(op)
invisible(rval)
}
I marked where the problem occur as:
================================================
==============Need to edit======================
op <- par(mar = c(2, 1, 1, 1))
================================================
After changing the line to par(mar=c(5, 5, 3, 10)) I got:

Error while plotting ODE phase potriat in R package phaseR

I am trying to plot a two-dimensional phase portrait in R using the phaseR package. This is an example of what I want to do:
Example that works
library(phaseR)
lotkaVolterra <- function(t, y, parameters) {
x <- y[1]
y <- y[2]
lambda <- parameters[1]
epsilon <- parameters[2]
eta <- parameters[3]
delta <- parameters[4]
dy <- numeric(2)
dy[1] <- lambda*x - epsilon*x*y
dy[2] <- eta*x*y - delta*y
list(dy)
}
then when I plot it I get
lotkaVolterra.flowField <- flowField(lotkaVolterra, x.lim = c(0, 5), y.lim = c(0, 10), parameters = c(2, 1, 3, 2), points = 19, add = FALSE)
grid()
lotkaVolterra.nullclines <- nullclines(lotkaVolterra, x.lim = c(-1, 5), y.lim = c(-1, 10), parameters = c(2, 1, 3, 2), points = 500)
y0 <- matrix(c(1, 2, 2, 2, 3, 4), ncol = 2, nrow = 3, byrow = TRUE)
lotkaVolterra.trajectory <- trajectory(lotkaVolterra, y0 = y0, t.end = 10, parameters = c(2, 1, 3, 2), colour = rep("black", 3))
this is the plot I get:
The problem
When I try to do the same with my equation however the vector space does not appear:
WalpeFun <- function(t, y, parameters) {
x <- y[1]
y <- y[2]
k <- parameters[1]
z <- parameters[2]
w <- parameters[3]
b <- parameters[4]
d <- parameters[5]
v <- parameters[6]
a <- parameters[7]
g <- parameters[8]
l <- parameters[9]
e <- parameters[10]
dy <- numeric(2)
dy[1] <- 2.5*(1-(x/k)^z)+g*l+w*e - b*(x*y/d^2+y^2)
dy[2] <- 2.5 * (1 - (y/x + v)^a)
list(dy)
}
Walpe.flowField <-flowField(WalpeFun, x.lim = c(0, 150), y.lim = c(-1, 50), parameters = c(120.73851, 0.51786, -0.75178, 0.00100, 1.00000, 500, 0.001, 0.01102, 320.995455, 5.582273) , points = 20, add = FALSE)
grid()
Walpe.nullclines <-nullclines(WalpeFun, x.lim = c(0, 150), y.lim = c(-1, 50), parameters = c(120.73851, 0.51786, -0.75178, 0.00100, 1.00000, 500, 0.001, 0.01102, 320.995455, 5.582273))
y0 <- matrix(c(8.2, 2), ncol = 2, nrow = 1, byrow = TRUE)
Walpe.trajectory <-trajectory(WalpeFun, y0 = y0, t.end = 100, parameters = c(120.73851, 0.51786, -0.75178, 0.00100, 1.00000, 500, 0.001, 0.01102, 320.995455, 5.582273),system = "two.dim", colour = "black")
I get this very different plot:
and get the following error:
Error in if ((dx[i, j] != 0) & (dy[i, j] != 0)) { : missing value where TRUE/FALSE needed
I don't understand why the vectors don show, or why the blue nullcline is missing
Mathematically your x.lim range exceeds the domain where the function can have a value. Because your dy[2] expression has x in the denominator of one of its terms, the function blows up at x == 0 and then there will be an NA in the dy[]-matrix that is internal to the function code. (There's a bit of an ambiguity in that your dy-object is a 2 element vector whereas looking at the code, the calculations are being stored in 2d-matrices named dx and dy.)
flowField #look at the code
png()
Walpe.flowField <-flowField(WalpeFun, x.lim = c(0.01, 150), y.lim = c(-1, 50), parameters = c(120.73851, 0.51786, -0.75178, 0.00100, 1.00000, 500, 0.001, 0.01102, 320.995455, 5.582273) , points = 20, add = FALSE, system="two.dim")
Walpe.nullclines <-nullclines(WalpeFun, x.lim = c(0.01, 150), y.lim = c(-1, 50), parameters = c(120.73851, 0.51786, -0.75178, 0.00100, 1.00000, 500, 0.001, 0.01102, 320.995455, 5.582273))
y0 <- matrix(c(8.2, 2), ncol = 2, nrow = 1, byrow = TRUE)
Walpe.trajectory <-trajectory(WalpeFun, y0 = y0, t.end = 100, parameters = c(120.73851, 0.51786, -0.75178, 0.00100, 1.00000, 500, 0.001, 0.01102, 320.995455, 5.582273),system = "two.dim", colour = "black")
dev.off()
I don't know why the nullclines don't appear, but I'm guessing there are features of the function that neither of us understands.

Handling axis with dates in twoord.plot (remove axis 3)

I am trying to use twoord.plot with different dates on x axis and counts for ly and percentages for ry, and I want to remove axis 3 or change its color. Setting axes = F does not work, neither does xaxt = 'n'.
In fact, axes = FALSE gives me this error message:
Error in plot.default(lx, ly, xlim = xlim, ylim = lylim, xlab = xlab, :
formal argument "axes" matched by multiple actual arguments
The solution given here:
Remove all axis values and labels in twoord plot does not work for me with different rx and lx.
Here is a similar code to that I'm using:
set.seed(123)
library(plotrix)
twoord.plot(
lx = seq(as.Date("2016-01-01"), as.Date("2017-01-01"), by = "days"),
ly = round(runif(367) * 6),
rx = seq(as.Date("2016-05-09"), as.Date("2017-01-12"), by = "days"),
ry = sort(rnorm(249, 60, 10)),
lylim = range(round(runif(367) * 6)) + c(0, 10),
rylim = range(sort(rnorm(249, 60, 10))) + c(-35, 10),
ylab.at = mean(round(runif(367) * 6)),
rylab.at = mean(sort(rnorm(249, 60, 10))),
rylab = "Percentages %", ylab = "No. of x",
type = c("l", "l"), lcol = "skyblue4", rcol = "chocolate1" ,
xtickpos = as.numeric(seq(as.Date("2016-01-01"), as.Date("2017-01-01"), by = "months")),
xticklab = seq(as.Date("2016-01-01"), as.Date("2017-01-01"), by = "months"))
Any ideas on how to this? Thanks in advance! :)
Just hack the twoord.plot function. Here's an example to make all axis labels black (Use twoord.plot2 instead of twoord.plot when creating the plot). If you want to remove the axes altogether, just comment (add # before the lines) Lines 88-90 (For ly) and Lines 123-125 (for ry). I have left notes for them in the function below.
twoord.plot2 = function (lx, ly, rx, ry, data = NULL, main = "", xlim = NULL,
lylim = NULL, rylim = NULL, mar = c(5, 4, 4, 4), lcol = 1,
rcol = 2, xlab = "", lytickpos = NA, ylab = "", ylab.at = NA,
rytickpos = NA, rylab = "", rylab.at = NA, lpch = 1, rpch = 2,
type = "b", xtickpos = NULL, xticklab = NULL, halfwidth = 0.4,
axislab.cex = 1, do.first = NULL, ...)
{
if (!is.null(data)) {
ly <- unlist(data[ly])
ry <- unlist(data[ry])
if (missing(lx))
lx <- 1:length(ly)
else lx <- unlist(data[lx])
if (missing(rx))
rx <- 1:length(ry)
else rx <- unlist(data[rx])
}
if (missing(lx))
lx <- 1:length(ly)
if (missing(ry)) {
if (missing(rx)) {
rx <- 1:length(ry)
ry <- ly
ly <- lx
lx <- 1:length(ly)
}
else {
ry <- rx
rx <- 1:length(ry)
}
}
oldmar <- par("mar")
par(mar = mar)
if (is.null(xlim))
xlim <- range(c(lx, rx))
if (missing(lx))
lx <- 1:length(ly)
if (is.null(lylim)) {
lylim <- range(ly, na.rm = TRUE)
lyspan <- diff(lylim)
if (lyspan == 0)
lyspan <- lylim[1]
lylim[2] <- lylim[2] + lyspan * 0.04
if (lylim[1] != 0)
lylim[1] <- lylim[1] - lyspan * 0.04
}
if (length(type) < 2)
type <- rep(type, 2)
if (match(type[1], "bar", 0)) {
oldcex <- par(cex = axislab.cex)
plot(lx, ly, xlim = xlim, ylim = lylim, xlab = xlab,
ylab = "", yaxs = "i", type = "n", main = "", axes = FALSE,
...)
par(oldcex)
if (!is.null(do.first))
eval(parse(text = do.first))
ybottom <- par("usr")[3]
if (lylim[1] < 0)
abline(h = 0, lty = 2)
rect(lx - halfwidth, ifelse(ly < 0, ly, ybottom), lx +
halfwidth, ifelse(ly > 0, ly, 0), col = lcol)
}
else {
oldcex <- par(cex = axislab.cex)
plot(lx, ly, xlim = xlim, ylim = lylim, xlab = xlab,
ylab = "", yaxs = "i", type = "n", main = "", axes = FALSE,
...)
par(oldcex)
if (!is.null(do.first))
eval(parse(text = do.first))
points(lx, ly, col = lcol, pch = lpch, type = type[1],
...)
}
title(main = main)
xylim <- par("usr")
box()
if (is.null(xticklab))
axis(1, cex.axis = axislab.cex)
else {
if (is.null(xtickpos))
xtickpos <- 1:length(xticklab)
axis(1, at = xtickpos, labels = xticklab, cex.axis = axislab.cex)
}
if (is.na(lytickpos[1]))
lytickpos <- pretty(ly)
if (is.na(ylab.at))
ylab.at <- mean(lytickpos)
color.axis(2, at = lytickpos, axlab = ylab, axlab.at = ylab.at, #LINE 88
col = "black", cex.axis = axislab.cex, #col = ifelse(is.na(lcol), 1, lcol), cex.axis = axislab.cex,
cex = axislab.cex) #LINE 90
if (is.null(rylim)) {
rylim <- range(ry, na.rm = TRUE)
ryspan <- diff(rylim)
if (ryspan == 0)
ryspan <- rylim[1]
rylim[2] <- rylim[2] + ryspan * 0.04
if (rylim[1] != 0)
rylim[1] <- rylim[1] - ryspan * 0.04
}
ymult <- diff(lylim)/diff(rylim)
yoff <- lylim[1] - rylim[1] * ymult
if (match(type[2], "bar", 0)) {
if (rylim[1] < 0)
abline("h", 0)
rect(rx - halfwidth, ifelse(ry < 0, ry, rylim[1] * ymult +
yoff), rx + halfwidth, ifelse(ry > 0, ry * ymult +
yoff, 0), col = rcol)
}
else points(rx, ry * ymult + yoff, col = rcol, pch = rpch,
type = type[2], ...)
if (is.na(rytickpos[1]))
rylabels <- pretty(rylim)
else rylabels <- rytickpos
if (min(rylabels) < rylim[1])
rylabels <- rylabels[rylabels >= rylim[1]]
if (max(rylabels) > rylim[2])
rylabels <- rylabels[rylabels <= rylim[2]]
axat <- rylabels * ymult + yoff
if (is.na(rylab.at))
rylab.at <- mean(rytickpos)
if (!is.na(rylab.at))
rylab.at <- rylab.at * ymult + yoff
color.axis(4, at = axat, labels = rylabels, axlab = rylab, #LINE 123
axlab.at = rylab.at, col = "black", #axlab.at = rylab.at, col = ifelse(is.na(rcol), 1, rcol),
cex.axis = axislab.cex, cex = axislab.cex) #LINE 125
par(mar = oldmar, new = FALSE, col.axis = "black")
}

Fanplot in R with other package than fanplot

I generally create a fanplot like this:
n.ahead <- 10
m <- matrix(,nrow = 5000,ncol = 10)
library(fanplot)
m[,1] <- rnorm(5000,0.01,sd = 0.005)
m[,2] <- rnorm(5000,0.02,0.006)
m[,3] <- rnorm(5000,0.03,0.008)
m[,4] <- rnorm(5000,0.04,0.01)
m[,5] <- rnorm(5000,0.06,0.013)
m[,6] <- rnorm(5000,0.1,0.015)
m[,7] <- rnorm(5000,0.11,0.02)
m[,8] <- rnorm(5000,0.13,0.025)
m[,9] <- rnorm(5000,0.14,0.05)
m[,10] <- rnorm(5000,0.18,0.07)
n.ahead <- 10
fancol <- colorRampPalette(c('black', 'white'))
plot(
NULL, type = 'n', lwd = 3, col = 'black',
xlim = c(0, n.ahead), ylab = 'Y', ylim = c(0,max(m)), xlab = 'Year',
las = 1, xaxt = 'n', main = 'Y'
)
fan(
m, fan.col = fancol, ln.col = 'grey', txt = c('90','95', '99'),
anchor = 0, frequency = 1, probs = c(seq(1, 99, 1), 99.9, 99.95, 99.99), ln =
c(50, 90, 99, 99.9, 99.95, 99.99)
)
axis(1, at = 0:n.ahead, tcl = 0.5)
axis(1, at = seq(0, n.ahead, 0.25), labels = FALSE, tcl = 0.25)
It does the trick in the sense that a fanlplot is created. However, I don't really like it. Are there alternatives with dynamic charts like we see in dygraphs and rCharts I can use in Shiny?
Thanks.

Resources