R loop xts plots - r

I am stuck on what is probably a simple problem: Loop on xts objects.
I would like to make four different plots for the elements in the basket: basket <- cbind(AAPLG, GEG, SPYG, WMTG)
> head(basket)
new.close new.close.1 new.close.2 new.close.3
2000-01-04 1.0000000 1.0000000 1.0000000 1.0000000
2000-01-05 1.0146341 0.9982639 1.0017889 0.9766755
2000-01-06 0.9268293 1.0115972 0.9856887 0.9903592
2000-01-07 0.9707317 1.0507639 1.0429338 1.0651532
2000-01-10 0.9536585 1.0503472 1.0465116 1.0457161
2000-01-11 0.9048780 1.0520833 1.0339893 1.0301664
This is my idea so far, as I cannot simply put in i as column name:
tickers <- c("AAPLG", "GEG", "SPYG", "WMTG")
par(mfrow=c(2,2))
for (i in 1:4){
print(plot(x = basket[, [i]], xlab = "Time", ylab = "Cumulative Return",
main = "Cumulative Returns", ylim = c(0.0, 3.5), major.ticks= "years",
minor.ticks = FALSE, col = "red"))
}
This is the error I get when running the script:
Error: unexpected ',' in " main = "Cumulative Returns","
> minor.ticks = FALSE, col = "red"))
Error: unexpected ',' in " minor.ticks = FALSE,"
> }
Error: unexpected '}' in "}"
Any help is very much appreciated.

As mentioned, remove the square brackets around i:
par(mfrow=c(2,2))
for (i in 1:4){
print(plot(x = basket[, i], xlab = "Time", ylab = "Cumulative Return",
main = "Cumulative Returns", ylim = c(0.0, 3.5), major.ticks= "years",
minor.ticks = FALSE, col = "red"))
}
But even better, assign names with cbind in building xts object or re-name your xts object like any data frame, then iterate across names for column referencing and titles:
Plot
# PASS NAMES WITH cbind
basket <- cbind(AAPLG=APPLG, GEG=GEG, SPYG=SPYG, WMTG=WMTG)
# RENAME AFTER cbind
# basket <- cbind(AAPLG, GEG, SPYG, WMTG)
# colnames(basket) <- c("AAPLG", "GEG", "SPYG", "WMTG")
par(mfrow=c(2,2))
sapply(names(basket), function(col)
print(plot(x = basket[, col], xlab = "Time", ylab = "Cumulative Return", data = basket,
main = paste(col, "Cumulative Returns"), ylim = c(0.0, 3.5),
major.ticks= "years", minor.ticks = FALSE, col = "red"))
)

Related

Extension to answered question: R - Defining a function which recognises arguments not as objects, but as being part of the call

I've followed the excellent answer, as described here: https://stackoverflow.com/a/59987272/7493594
But how can I make it work with ggadjustedcurves?
myfun <- function(TimeVar, EventVar, CoxVar, CoxData){
TimeVar <- as.name(TimeVar)
EventVar <- as.name(EventVar)
CoxVar <- as.name(CoxVar)
CoxModel <- eval(bquote(coxph(Surv(.(TimeVar), .(EventVar)) ~.(CoxVar), data = .(CoxData))))
ggadjustedcurves(CoxModel,
variable = CoxVar,
xlab = "Years",
ylab = "Survival",
ggtheme = theme_survminer(),
size = 2, palette = "lancet",
data = CoxData)
I guess you're after something like this?
library(survminer)
library(survival)
myfun <- function(TimeVar, EventVar, CoxVar, CoxData) {
TimeVar <- as.name(TimeVar)
EventVar <- as.name(EventVar)
CoxVar_char <- CoxVar # Need to store `CoxVar` as string
CoxVar <- as.name(CoxVar)
CoxData <- as.name(CoxData)
CoxModel <- eval(bquote(
coxph(Surv(.(TimeVar), .(EventVar)) ~.(CoxVar), data = .(CoxData))))
ggadjustedcurves(
CoxModel,
variable = CoxVar_char, # `variable` needs to be a string
xlab = "Years",
ylab = "Survival",
ggtheme = theme_survminer(),
size = 2, palette = "lancet",
data = eval(CoxData)) # Eval `CoxData` as symbol
}
myfun("stop", "event", "size", "bladder")

R: How to plot multiple ARIMA forecasts on the same time-series

I would like to plot several forecasts on the same plot in different colours, however, the scale is off.
I'm open to any other methods.
reproducible example:
require(forecast)
# MAKING DATA
data <- c(3.86000, 19.55810, 19.51091, 20.74048, 20.71333, 29.04191, 30.28864, 25.64300, 23.33368, 23.70870 , 26.16600 ,27.61286 , 27.88409 , 28.41400 , 24.81957 , 24.60952, 27.49857, 32.08000 , 29.98000, 27.49000 , 237.26150, 266.35478, 338.30000, 377.69476, 528.65905, 780.00000 )
a.ts <- ts(data,start=c(2005,1),frequency=12)
# FORECASTS
arima011_css =stats::arima(x = a.ts, order = c(0, 1, 1), method = "CSS") # css estimate
arima011_forecast = forecast(arima011_css, h=10, level=c(99.5))
arima321_css =stats::arima(x = a.ts, order = c(3, 2, 1), method = "CSS") # css estimate
arima321_forecast = forecast(arima321_css, h=10, level=c(99.5))
# MY ATTEMPT AT PLOTS
plot(arima321_forecast)
par(new=T)
plot(arima011_forecast)
Here is something similar to #jay.sf but using ggplot2.
library(ggplot2)
autoplot(a.ts) +
autolayer(arima011_forecast, series = "ARIMA(0,1,1)", alpha = 0.5) +
autolayer(arima321_forecast, series = "ARIMA(3,2,1)", alpha = 0.5) +
guides(colour = guide_legend("Model"))
Created on 2020-05-19 by the reprex package (v0.3.0)
You could do a manual plot using a sequence of dates.
rn <- format(seq.Date(as.Date("2005-01-01"), by="months", length.out=12*3), "%Y.%m")
Your ARIMAs you'll need as.matrix form.
arima321_mat <- as.matrix(as.data.frame(arima321_forecast))
arima011_mat <- as.matrix(as.data.frame(arima011_forecast))
Some colors with different alpha=.
col.1 <- rainbow(2, ,.7)
col.2 <- rainbow(2, ,.7, alpha=.2)
For the CIs use polygon.
plot(data, type="l", xlim=c(1, length(rn)), ylim=c(0, 3500), xaxt="n", main="Forecasts")
axis(1, axTicks(1), labels=F)
mtext(rn[(seq(rn)-1) %% 5 == 0], 1, 1, at=axTicks(1))
lines((length(data)+1):length(rn), arima321_mat[,1], col=col.1[1], lwd=2)
polygon(c(27:36, 36:27), c(arima321_mat[,2], rev(arima321_mat[,3])), col=col.2[1],
border=NA)
lines((length(data)+1):length(rn), arima011_mat[,1], col=col.1[2], lwd=3)
polygon(c(27:36, 36:27), c(arima011_mat[,2], rev(arima011_mat[,3])), col=col.2[2],
border=NA)
legend("topleft", legend=c("ARIMA(3,2,1)", "ARIMA(0,1,1)"), col=col.1, lwd=2, cex=.9)
Edit: To avoid the repetition of lines and polygon calls, you may unite them using Map.
mats <- list(arima321_mat, arima011_mat) ## put matrices into list
plot(.)
axis(.)
mtext(.)
Map(function(i) {
lines((length(data)+1):length(rn), mats[[i]][,1], col=col.1[i], lwd=2)
polygon(c(27:36, 36:27), c(mats[[i]][,2], rev(mats[[i]][,3])), col=col.2[i], border=NA)
}, 1:2)
legend(.)
require(forecast)
data <- c(3.86000, 19.55810, 19.51091, 20.74048, 20.71333, 29.04191, 30.28864, 25.64300, 23.33368, 23.70870 , 26.16600 ,27.61286 , 27.88409 , 28.41400 , 24.81957 , 24.60952, 27.49857, 32.08000 , 29.98000, 27.49000 , 237.26150, 266.35478, 338.30000, 377.69476, 528.65905, 780.00000 )
a.ts <- ts(data,start=c(2005,1),frequency=12)
arima011_css =stats::arima(x = a.ts, order = c(0, 1, 1), method = "CSS") # css estimate
arima011_forecast = predict(arima011_css, n.ahead = 2)$pred
arima321_css =stats::arima(x = a.ts, order = c(3, 2, 1), method = "CSS") # css estimate
arima321_forecast = predict(arima321_css, n.ahead = 2)$pred
plot(a.ts, type = "o", xlim = c(2005, 2007.5) , ylim = c(-1, 1200) , ylab = "price" ,main = "2 month Forecast")
range = c(2007+(3/12), 2007+(4/12)) # adding the dates for the prediction
lines(y = arima011_forecast , x = range , type = "o", col = "red")
lines(y = arima321_forecast, x = range , type = "o", col = "blue")

Assigning type to xyplot

Complete beginner at R here trying to perform nonmetric multidimensional scaling on a 95x95 matrix of similarities where 8 corresponds to very similar and 1 corresponds to very dissimilar. I also have an additional column (96th) signifying type and ranging from 0 to 1.
First I load the data:
dsimilarity <- read.table("d95x95matrix.txt",
header = T,
row.names = c("Y1", "Y2", "Y3", "Y4", "Y5", "Y6", "Y7", "Y8", "Y9", "Y10", "Y11", "Y12", "Y13", "Y14", "Y15", "Y16", "Y17", "Y18", "Y19", "Y20",
"Y21", "Y22", "Y23", "Y24", "Y25", "Y26", "Y27", "Y28", "Y29", "Y30", "Y31", "Y32", "Y33", "Y34", "Y35", "Y36", "Y37", "Y38", "Y39", "Y40",
"Y41", "Y42", "Y43", "Y44", "Y45", "Y46", "Y47", "Y48", "Y49", "Y50", "Y51", "Y52", "Y53", "Y54", "Y55", "Y56", "Y57", "Y58", "Y59", "Y60",
"Y61", "Y62", "Y63", "Y64", "Y65", "Y66", "Y67", "Y68", "Y69", "Y70", "Y71", "Y72", "Y73", "Y74", "Y75", "Y76", "Y77", "Y78", "Y79", "Y80",
"Y81", "Y82", "Y83", "Y84", "Y85", "Y86", "Y87", "Y88", "Y89", "Y90", "Y91", "Y92", "Y93", "Y94", "Y95"))
I convert the matrix of similarities into a matrix of dissimilarities, and exclude the 96th column:
ddissimilarity <- dsimilarity; ddissimilarity[1:95, 1:95] = 8 - ddissimilarity[1:95, 1:95]
Then I perform the nonmetric MDS using the Smacof function:
ordinal.mds.results <- smacofSym(ddissimilarity[1:95, 1:95],
type = c("ordinal"),
ndim = 2,
ties = "primary",
verbose = T )
I create a new data frame (I'm following a guide and don't really know what's going on here):
mds.config <- as.data.frame(ordinal.mds.results$conf)
All well and good thus far (to my knowledge). However at this point I will try to create an xyplot of the data and get a good result using this code:
xyplot(D2 ~ D1, data = mds.config,
aspect = 1,
main = "Figure 1. MDS solution",
panel = function (x, y) {
panel.xyplot(x, y, col = "black")
panel.text(x, y-.03, labels = rownames(mds.config),
cex = .75)
},
xlab = "MDS Axis 1",
ylab = "MDS Axis 2",
xlim = c(-1.1, 1.1),
ylim = c(-1.1, 1.1))
Now I want to create a figure that incorporates the type in column 96th and assigns different colors to observations of the two different types. However, can't quite figure out how to do so. Does anyone have any ideas of where I'm going wrong here?
xyplot(D2 ~ D1, data = mds.config ~ ddissimilarity[96:96, 96:96],
aspect = 1,
main = "Figure 1. MDS solution",
panel = function (x, y) {
panel.xyplot(x, y, col = "black")
panel.text(x, y-.03, labels = rownames(mds.config),
cex = .75)
},
xlab = "MDS Axis 1",
ylab = "MDS Axis 2",
xlim = c(-1.1, 1.1),
ylim = c(-1.1, 1.1),
group = "Type")

r density plot - fill area under curve [duplicate]

This question already has answers here:
Shading a kernel density plot between two points.
(5 answers)
Closed 7 years ago.
I've written code to plot density data for variations of an A/B test. I'd like to improve the visual by shading (with the fill being slightly transparent) the area below each curve. I'm currently using matplot, but understand ggplot might be a better option.
Any ideas? Thanks.
# Setup data frame - these are results from an A/B experiment
conv_data = data.frame(
VarNames = c("Variation 1", "Variation 2", "Variation 3") # Set variation names
,NumSuccess = c(1,90,899) # Set number of successes / conversions
,NumTrials = c(10,100,1070) # Set number of trials
)
conv_data$NumFailures = conv_data$NumTrials - conv_data$NumSuccess # Set number of failures [no conversions]
num_var = NROW(conv_data) # Set total number of variations
plot_col = rainbow(num_var) # Set plot colors
get_density_data <- function(n_var, s, f) {
x = seq(0,1,length.out=100) # 0.01,0.02,0.03...1
dens_data = matrix(data = NA, nrow=length(x), ncol=(n_var+1))
dens_data[,1] = x
# set density data
for(j in 1:n_var) {
# +1 to s[], f[] to ensure uniform prior
dens_data[,j+1] = dbeta(x, s[j]+1, f[j]+1)
}
return(dens_data)
}
density_data = get_density_data(num_var, conv_data$NumSuccess, conv_data$NumFailures)
matplot(density_data[,1]*100, density_data[,-1], type = "l", lty = 1, col = plot_col, ylab = "Probability Density", xlab = "Conversion Rate %", yaxt = "n")
legend("topleft", col=plot_col, legend = conv_data$VarNames, lwd = 1)
This produces the following plot:
# Setup data frame - these are results from an A/B experiment
conv_data = data.frame(
VarNames = c("Variation 1", "Variation 2", "Variation 3") # Set variation names
,NumSuccess = c(1,90,899) # Set number of successes / conversions
,NumTrials = c(10,100,1070) # Set number of trials
)
conv_data$NumFailures = conv_data$NumTrials - conv_data$NumSuccess # Set number of failures [no conversions]
num_var = NROW(conv_data) # Set total number of variations
plot_col = rainbow(num_var) # Set plot colors
get_density_data <- function(n_var, s, f) {
x = seq(0,1,length.out=100) # 0.01,0.02,0.03...1
dens_data = matrix(data = NA, nrow=length(x), ncol=(n_var+1))
dens_data[,1] = x
# set density data
for(j in 1:n_var) {
# +1 to s[], f[] to ensure uniform prior
dens_data[,j+1] = dbeta(x, s[j]+1, f[j]+1)
}
return(dens_data)
}
density_data = get_density_data(num_var, conv_data$NumSuccess, conv_data$NumFailures)
matplot(density_data[,1]*100, density_data[,-1], type = "l",
lty = 1, col = plot_col, ylab = "Probability Density",
xlab = "Conversion Rate %", yaxt = "n")
legend("topleft", col=plot_col, legend = conv_data$VarNames, lwd = 1)
## and add this part
for (ii in seq_along(plot_col))
polygon(c(density_data[, 1] * 100, rev(density_data[, 1] * 100)),
c(density_data[, ii + 1], rep(0, nrow(density_data))),
col = adjustcolor(plot_col[ii], alpha.f = .25))
Was able to answer own question with:
df = as.data.frame(t(conversion_data))
dfs = stack(df)
ggplot(dfs, aes(x=values)) + geom_density(aes(group=ind, colour=ind, fill=ind), alpha=0.3)

Proper density plotting

I have 3 columns of data. In columns data ranging from approximately 0,0727
to 10,2989.
and this is how it looks:
http://i61.tinypic.com/2uen3hz.jpg
My Code
MyData <- read.csv2(file="C:/Users/Sysop/Desktop/Koncentracija.csv",header=T,sep=";")
MyData
Data_1<-MyData$Sul311
Data_2<-MyData$Sul322
Data_3<-MyData$Sul333
Data_1_density<- density(Data_1,na.rm = TRUE)
Data_2_density<- density(Data_2,na.rm = TRUE)
Data_3_density<- density(Data_3,na.rm = TRUE)
xlim <- range(Data_1_density$x,Data_2_density$x,Data_3_density$x, na.rm = TRUE)
ylim <- range(Data_1_density$y, Data_2_density$y, Data_3_density$y, na.rm = TRUE)
Col_1 <- rgb(1,0,0,0.4)
Col_2 <- rgb(0,0,1,0.4)
Col_3 <- rgb(0,1,0,0.4)
plot(Data_1_density, xlim = xlim, ylim = ylim, xlab = 'Zn concentracion, mg/l',main = 'Distribution of data', panel.first = grid(nx = 10, ny = 10))
polygon(Data_1_density, density = -1, col = Col_1)
polygon(Data_2_density, density = -1, col = Col_2)
polygon(Data_3_density, density = -1, col = Col_3)
legend('topright',c('distribution 1 ','distribution 2','distribution 3'),cex=1.0, fill = c(Col_1, Col_2, Col_3), bty = 'n',border = NA)
But as we can see density plots begining from negative values, but my data does not have any negative values. One column missing one value so R shows as NA, but I use (na.rm = TRUE) to ignore NA values.
So is these density plots plotted correctly or not?
Here is my data:
Sul311 Sul322 Sul333
1,8032 NA 2,3981
3,4949 3,1696 1,8218
0,5856 0,5577 0,0837
0,1859 1,5894 0,093
1,4686 1,45 2,9744
0,079 0,0727 0,0543
1,0317 1,0782 2,7513
0,5112 0,5484 0,9295
1,3943 1,1805 2,7513
1,1526 1,1619 2,6305
1,3013 10,2989 5,577
0,5949 0,5856 0,725
0,1766 0,2696 1,6917
0,4229 0,3309 1,1089
1,1953 0,3328 1,6787
1,4853 0,6116 1,8367
0,4443 0,3514 1,2939
0,5912 0,3309 1,2901
you can define the begining or the "first value" with the from argument :
density(x, na.rm=T, from=min(x, na.rm=T))
for instance

Resources