R - Why don't my curves start at (0,1)? - r

I'm just trying to plot three curves on a chart, which all must start at (0,1) and end at (30, 0.51). The problem is the curves seems to start at about (2,1) and end at (31,0.51). My code is:
require(graphics)
library(latex2exp)
Linear<-c( 1,0.983666667,0.967333333,0.951,0.934666667,0.918333333,0.902,0.885666667,
0.869333333,0.853,0.836666667,0.820333333,0.804,0.787666667,0.771333333,
0.755,0.738666667,0.722333333,0.706,0.689666667,0.673333333,0.657,0.640666667,
0.624333333,0.608,0.591666667,0.575333333,0.559,0.542666667,0.526333333,0.51)
SqRt<-c( 1 , 0.910538649 , 0.873482544 , 0.845048395 , 0.821077298 ,
0.799958338 , 0.780865338 , 0.763307513 , 0.746965088 , 0.731615947 ,
0.717098368 , 0.703290265 , 0.690096789 , 0.677442512 , 0.665266275 ,
0.653517677 , 0.642154596 , 0.6311414 , 0.620447632 , 0.610047011 ,
0.599916675 , 0.590036587 , 0.580389069 , 0.570958432 , 0.561730676 ,
0.552693245 , 0.543834825 , 0.535145184 , 0.526615026 , 0.518235881 , 0.51 )
CubeRt<-c( 1 , 0.842124513 , 0.801135304 , 0.772387515 , 0.749504067 , 0.730181506 ,
0.71329249 , 0.698190887 , 0.684467813 , 0.671846185 , 0.660128536 ,
0.649168592 , 0.638854625 , 0.629099142 , 0.619832193 , 0.610996874 ,
0.602546197 , 0.59444086 , 0.586647616 , 0.579138061 , 0.571887715 ,
0.56487531 , 0.558082241 , 0.551492126 , 0.545090459 , 0.538864322 ,
0.532802159 , 0.526893586 , 0.521129232 , 0.515500609 , 0.51 )
g_range <- range(0, Linear, SqRt,CubeRt,na.rm = TRUE)
plot(Linear, type="l",lwd=2, col="blue", ylim=g_range,
axes=FALSE, ann=FALSE,lty=1)
axis(1, at=c(0,5,10,15,20,25,30))
axis(2, las=1)
box()
lines(SqRt, type="l", pch=22, lty=1,lwd=2, col="red")
lines(CubeRt, type="l", pch=24, lty=1,lwd=2, col="black")
title(xlab="mmh/RH", col.lab=rgb(0,0,0))
title(ylab="Availability", col.lab=rgb(0,0,0))
plot_colors <- c("blue","red", "black")
text <- c("Linear", "Square Root", "Cube Root")
legend(x=14, y=1.0, legend=text, fill=plot_colors, ncol=3, xpd=NA)
and the plot looks like this.

If you don't supply both x and y values, R will just start plotting 1, 2, ..., to the total number of values you provide. If you want to start at zero, it's better to pass in the x values explicitly. For example
plot(x=0:30, y=Linear, type="l",lwd=2, col="blue", ylim=g_range,
axes=FALSE, ann=FALSE,lty=1)
lines(x=0:30, y=SqRt, type="l", pch=22, lty=1, lwd=2, col="red")
lines(x=0:30, y=CubeRt, type="l", pch=24, lty=1, lwd=2, col="black")

Related

Use i in variable r

I want to use the i variable to loop over this piece of code, each iteration changing FAQ$q1 to FAQ$q2, FAQ$q3. How can I do this?
for(i in 1: 19){
yes <- table(FAQ$q1)[1]
no <- table(FAQ$q1)[2]
b <- barplot(table(FAQ$q1),
main="Did you have any difficulties using the chatbot?",
ylab="Count",
names.arg = c("yes", "no"),
col="blue",
ylim = c(0,28))
abline(v=c(1.3) , col="grey")
text(b, y=c(yes+1,no+1), paste("n: ", c(yes,no) , sep=""), cex=1, col = "red")
}
We can use paste to create a string for the column name and extract with [[ (as $ will try to match literally). If we want to redirect the plots to a single pdf, then write the plots to pdf. In the code, table function was applied on the same column multiple times, instead, do it once and create an object ('tbl1') which is reused as necessary
pdf("path/to/file.pdf")
for(i in 1:19){
colnm <- paste0("q", i)
tbl1 <- table(FAQ[[colnm]])
yes <- tbl1[1]
no <- tbl1[2]
b <- barplot(tbl1,
main="Did you have any difficulties using the chatbot?",
ylab="Count",
names.arg = c("yes", "no"),
col="blue",
ylim = c(0,28))
abline(v=c(1.3) , col="grey")
text(b, y=c(yes+1,no+1), paste("n: ", c(yes,no) , sep=""), cex=1, col = "red")
}
dev.off()
The difference in paste0 and paste is in the sep. By default paste uses sep = " " where as it is "" in paste0

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")

Scaling radar plot for large value in R(with the data)

I have a data set for which I want to create a radar plot
str(trial4)
'data.frame': 4 obs. of 6 variables:
$ Var1 : Factor w/ 4 levels "2009-04-01","2010-04-01",..: 1 2 3 4
$ Arsenic : int 66 8 8 5
$ Fluoride: int 11775 10788 10724 7130
$ Iron : int 103 60 54 46
$ Nitrate : int 927 856 1106 624
$ Salinity: int 24787 23168 20258 18924
My radar plot code executes fine and I get the plot like this
radarchart(trial4,seg=6)
colors_border=c( rgb(0.2,0.5,0.5,0.9), rgb(0.8,0.2,0.5,0.9) , rgb(0.7,0.5,0.1,0.9) )
colors_in=c( rgb(0.2,0.5,0.5,0.4), rgb(0.8,0.2,0.5,0.4) , rgb(0.7,0.5,0.1,0.4) )
radarchart( trial4 , axistype=1 ,
#custom polygon
pcol=colors_border , pfcol=colors_in , plwd=2 , plty=1,
#custom the grid
cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8,
#custom labels
vlcex=0.8
)
legend(x=0.7, y=1, legend = rownames(trial4[-c(1,2),]), bty = "n", pch=20 , col=colors_in , text.col = "grey", cex=1.2, pt.cex=3)
As one can see, the problem is the scaling I cannot fit in the plot. I searched online, but it's not clear how I can make the polygon fit inside the grid of the radar plot. I tried adding xlim and ylim:
radarchart(trial4,seg=6)
colors_border=c( rgb(0.2,0.5,0.5,0.9), rgb(0.8,0.2,0.5,0.9) , rgb(0.7,0.5,0.1,0.9) )
colors_in=c( rgb(0.2,0.5,0.5,0.4), rgb(0.8,0.2,0.5,0.4) , rgb(0.7,0.5,0.1,0.4) )
radarchart( trial4 , axistype=1 ,
#custom polygon
pcol=colors_border , pfcol=colors_in , plwd=2 , plty=1,
#custom the grid
cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8,
#custom labels
vlcex=0.8,xlim=c(0,2),ylim=c(0,10)
)
legend(x=0.7, y=1, legend = rownames(trial4[-c(1,2),]), bty = "n", pch=20 , col=colors_in , text.col = "grey", cex=1.2, pt.cex=3)
but still I am not able to scale this properly.
Is there any parameter I am missing?.
so here is my data , and the package i am using is fmsb
var1<-c("2009-04-01","2010-04-01","2011-04-01","2012-04-01")
Arsenic<-c(66,8,8,5)
Fluoride<-c(11775,10788,10724,7130)
Iron<-c(103,60,54,46)
Nitrate<-c(927,856,1106,624)
Salinity<-c(24787,23168,20258,18924)
trail4<-as.data.frame(var1,Arsenic,Fluoride,Iron,Nitrate,Salinity)

Superimpose posterior distribution on mean like cat's eye visualization from cumming

I personally like the cat's eye visualization of Cumming that superimposes a sampling distribution over a point estimate:
I would also like to do this with the posterior distribution that is obtained by the Scripts of Kruschke (2015):
plotMCMC( mcmcCoda , data=myData ,
compValMu=100.0 , ropeMu=c(99.0,101.0) ,
compValSigma=15.0 , ropeSigma=c(14,16) ,
compValEff=0.0 , ropeEff=c(-0.1,0.1) ,
pairsPlot=TRUE , showCurve=FALSE ,
saveName=fileNameRoot , saveType=graphFileType )
# Set up window and layout:
openGraph(width=6.0,height=8.0*3/5)
layout( matrix( c(2,3,5, 1,4,6) , nrow=3, byrow=FALSE ) )
par( mar=c(3.5,3.5,2.5,0.5) , mgp=c(2.25,0.7,0) )
# Select thinned steps in chain for plotting of posterior predictive curves:
nCurvesToPlot = 20
stepIdxVec = seq( 1 , chainLength , floor(chainLength/nCurvesToPlot) )
# Compute limits for plots of data with posterior pred. distributions
y = data
xLim = c( min(y)-0.1*(max(y)-min(y)) , max(y)+0.1*(max(y)-min(y)) )
xBreaks = seq( xLim[1] , xLim[2] ,
length=ceiling((xLim[2]-xLim[1])/(sd(y)/4)) )
histInfo = hist(y,breaks=xBreaks,plot=FALSE)
yMax = 1.2 * max( histInfo$density )
xVec = seq( xLim[1] , xLim[2] , length=501 )
#-----------------------------------------------------------------------------
# Plot data y and smattering of posterior predictive curves:
histInfo = hist( y , prob=TRUE , xlim=xLim , ylim=c(0,yMax) , breaks=xBreaks,
col="red2" , border="white" , xlab="y" , ylab="" ,
yaxt="n" , cex.lab=1.5 , main="Data w. Post. Pred." )
for ( stepIdx in 1:length(stepIdxVec) ) {
lines(xVec, dt( (xVec-mu[stepIdxVec[stepIdx]])/sigma[stepIdxVec[stepIdx]],
df=nu[stepIdxVec[stepIdx]] )/sigma[stepIdxVec[stepIdx]] ,
type="l" , col="skyblue" , lwd=1 )
}
text( max(xVec) , yMax , bquote(N==.(length(y))) , adj=c(1.1,1.1) )
#-----------------------------------------------------------------------------
histInfo = plotPost( mu , cex.lab = 1.75 , showCurve=showCurve ,
compVal=compValMu , ROPE=ropeMu ,
xlab=bquote(mu) , main=paste("Mean") ,
col="skyblue" )
#-----------------------------------------------------------------------------
histInfo = plotPost( sigma , cex.lab=1.75 , showCurve=showCurve ,
compVal=compValSigma , ROPE=ropeSigma , cenTend="mode" ,
xlab=bquote(sigma) , main=paste("Scale") ,
col="skyblue" )
#-----------------------------------------------------------------------------
effectSize = ( mu - compValMu ) / sigma
histInfo = plotPost( effectSize , compVal=compValEff , ROPE=ropeEff ,
showCurve=showCurve , cenTend="mode" ,
xlab=bquote( ( mu - .(compValMu) ) / sigma ),
cex.lab=1.75 , main="Effect Size" ,
col="skyblue" )
#-----------------------------------------------------------------------------
postInfo = plotPost( log10(nu) , col="skyblue" , # breaks=30 ,
showCurve=showCurve ,
xlab=bquote("log10("*nu*")") , cex.lab = 1.75 ,
cenTend="mode" ,
main="Normality" ) # (<0.7 suggests kurtosis)
Which looks in the end like this for the mean
Is it possible to superimpose the histogram on the mean like Cumming does it?
I've created a function called plotViolin for another application that should do what you want, or at least be easily modifiable to the specifics of your application. You can find the function about half way down the R script linked here: https://osf.io/wt4vf/

Cannot write chinese text using CairoPDF in R

I am using cairo pdf as suggested in my previous question
How to plot chinese characters on pdf?
for generating chinese text on R.
library(Cairo)
mydata = matrix( c( 2:6, c( 2,4,2,6,3 ) ), nrow= 2 )
mylabs = c( "木材", "表", "笔", "垃圾桶", "杯" )
CairoPDF("Report_chinese.pdf", family="GB1")
barplot( mydata, beside=T, horiz= "T", names.arg= mylabs, las= 1, col= c( "red", "blue" ) )
dev.off()
But there is no chinese text on bar plot. How can i fix this pblm?
Regards
cairo_pdf() works for me:
mydata = matrix( c( 2:6, c( 2,4,2,6,3 ) ), nrow= 2 )
mylabs = c( "木材", "表", "笔", "垃圾桶", "杯" )
cairo_pdf("Report_chinese.pdf")
barplot( mydata, beside=T, horiz= "T", names.arg= mylabs, las= 1, col= c( "red", "blue" ) )
dev.off()
If you want to use the Cairo library, you have to first define a font that has the CJK glyphs (EDIT: per request in comments, this example uses different fonts for labels and title):
library(Cairo)
CairoFonts(regular="AR PL UKai CN:Book", bold="Century Schoolbook L:Italic")
CairoPDF("Report_chinese.pdf")
barplot( mydata, beside=T, horiz= "T", names.arg= mylabs, las= 1, col= c( "red", "blue" ) )
mtext("This is the title", side=3, line=1, font=2)
dev.off()
Note that the arguments to CairoFonts() are just arbitrary pointers: I have used the bold= argument to specify an italic typeface, and access it using font=2 in the call to mtext() (see the font argument in ?par). Be sure to substitute "AR PL UKai CN:Book" and "Century Schoolbook L:Italic" for fonts that you actually have on your system.
If you don't like that method, you can get the same result by calling CairoFonts() multiple times:
CairoFonts(regular="AR PL UKai CN:Book")
CairoPDF("Report_chinese.pdf")
barplot( mydata, beside=T, horiz= "T", names.arg= mylabs, las= 1, col= c( "red", "blue" ) )
CairoFonts(regular="Century Schoolbook L:Italic")
mtext("This is the title", side=3, line=1) #implicit argument: font=1
dev.off()

Resources