How to overlay two lines using the -plot- function in R - r

I am using R version 3.6.0. I am trying to overlay 3 lines on a single plot. I have done this successfully in the past using identical code and for some reason it doesn't seem to be working. I have the following RWE:
y.l <- function(x){0.024 - 0.00004*x + 0.00001*(10-16.8764)}
y.a <- function(x){0.024 - 0.00004*x}
y.h <- function(x){0.024 - 0.00004*x + 0.00001*(20-16.8764)}
png("yplot.png")
yplot <- plot(y.l(1:800),
type="l", lty=2,
xlab="x", ylab="y", main="Getting better :/",
ylim=c(-0.025,0.025))
lines(1:800, lty=1, y.a(1:800))
lines(1:800, lty=3, y.h(1:800))
dev.off()
which produces the following plot:
For some reason it is ignoring the extra -lines()- code. Is there some obvious mistake I am overlooking after staring at a computer all day? I have done this exact same thing before and I cannot for the life of me figure it out. And yes I have expanded the y-axis to see if they were hiding above or below and they aren't.

Your 3 lines are plotted, it is because of your function that you can't see them.
Here the output of your three function:
> head(y.a(1:800))
[1] 0.02396 0.02392 0.02388 0.02384 0.02380 0.02376
> head(y.h(1:800))
[1] 0.02399124 0.02395124 0.02391124 0.02387124 0.02383124 0.02379124
> head(y.l(1:800))
[1] 0.02389124 0.02385124 0.02381124 0.02377124 0.02373124 0.02369124
You can see that your three function give almost the same results, it because of your 0.00001*(10-16.8764) that's is basically to small to modify your output.
If you zoom enough on the plot:
yplot <- plot(y.l(1:800),
type="l", lty=2,
xlab="x", ylab="y", main="Getting better :/",
ylim=c(.023,0.024),
xlim=c(0,30))
lines(1:800, lty=1, y.a(1:800))
lines(1:800, lty=3, y.h(1:800))
You can see the three lines:
I think you need to change the last parameter of your function if you want to see a dramatic difference between your lines.

Related

Can't change axes in R for density plots when using mixtools

This should be easy to fix, I genuinely don't know what is wrong.
Suppose I wanted to perform the EM algorithm for the Old Faithful data in R and plot the results:
install.packages('mixtools')
library('mixtools')
test<-normalmixEM(faithful$waiting, k=2)
plot(test, which=2, xlim= c(30, 100))
lines(density(faithful$waiting), lty=2, lwd=2)
This works.
But if I wanted to change the x-label or y-axis I get an error message:
plot(test, which=2, xlim= c(30, 100), xlab="", ylim= c(0, 0.06))
lines(density(faithful$waiting), lty=2, lwd=2)
The message is:
argument 4 matches multiple formal arguments
Can someone please help me out? What am I doing wrong? I'm really puzzled.
Thanks!
From the documentation you need to follow this form:
plot(x, whichplots = 1,
loglik = 1 %in% whichplots,
density = 2 %in% whichplots,
xlab1="Iteration", ylab1="Log-Likelihood",
main1="Observed Data Log-Likelihood", col1=1, lwd1=2,
xlab2=NULL, ylab2=NULL, main2=NULL, col2=NULL,
lwd2=2, alpha = 0.05, marginal = FALSE, ...)
you'll need to use xlab2 = ...
plot() is a generic function that actually calls a more specific function (called a "method") depending on what you are trying to plot (see this chapter from Hadley Wickham's Advanced R book for details). In this case, you are feeding-in an object of class "mixEM" to plot(). You can see this by running, e.g.:
class(test)
The generic function plot() is calling the method plot.mixEM() because you are feeding in an object of type "mixEM". To see which parameters of plot.mixEM() you can control, check out that function's help page
?plot.mixEM
The helpfile makes it clear that you need xlab2 as an argument instead of xlab. However, I don't immediately see how to change ylim, so you should view the source code for plot.mixEM to see if there's a way to adjust it other components of the graph:
getAnywhere(plot.mixEM)

How to combine VaR graphics?

I want to programm a rolling Value at Risk by hand. So I don't want to use the VaR from the PerformanceAnalytics package. I want to plot after calculations against the log-returns of a time series.
Input:
getSymbols('^GDAXI', src='yahoo', return.class='ts',from="2005-01-01", to="2015-01-01")
GDAXI.DE=GDAXI[ , "GDAXI.Close"]
log_r1=diff(log(GDAXI.DE)) #log_r1=data
alpha=0.95
The VaR function:
VatR=function(data, alpha)
{
x=diff(log(data))
mu=mean(x)
sigma=sqrt(var(x))
quant=qnorm(alpha, mean=0, sd=1)
vatr=tail(data,n=1)*(1-exp((-sigma)*quant+mu))
}
data=GDAXI.DE
alpha=0.95
t=125
l=(-1)*diff(data) #if GDAXI used code must be changed here diff
loss=c(0,l)
ValueatRisk=matrix(rep(0),length(data),1)
violations=matrix(rep(0),length(data),1)
for(i in (t+1):length(data))
{
ValueatRisk[i]=VatRnorm(data[(i-t):(i-1)] ,alpha) #failure source
violations[i]=(loss[i] > ValueatRisk[i])
}
outputtheo=(1-alpha)*(length(data)-t)
print(outputtheo)
outputreal=sum(violations)
print(outputreal)
I want to combine these graphics. It seems to be a scaling problem, I tried qplot, ggplot and so on without success.
graph1=plot(loss[(t+1):length(data)], type="l", col="blue")
graph2=plot(ValueatRisk[(t+1):length(data)], type="l", col="red")
How to bring them together in one plot?
If plotting is the only issue now, I think this will produce what you want.
plot(loss[(t+1):length(data)], type="l", col="blue")
lines(ValueatRisk[(t+1):length(data)], type="l", col="red")
(And BTW, your code won't run as is because VatRnorm() inside the loop is really the old/original VatR().)

plot several linegraphs in one image using R

I am an absolute beginner in R. so this is probably a stupid question.
I have a table like this (csv format):
,1A+,2A+,3A-,3A+,5A-,5A+,6A-,6A+,7A-,7A+
6,4.530309305,5.520356001,3.437626731,5.146758132,,4.355022819,,4.191337618,,4.076583859
10,8.697814022,9.765817956,,9.636004092,3.725756716,8.600484774,3.457423715,8.358842335,2.246622784,7.244668991
12,,,8.176341701,,,,,,,
17,,,,,6.24785396,,5.077069513,,3.137524578
I want to create a line graph in R plotting all the different Y values (1A+, 2A+, etc) vs the Y values (6,10,12,17).
I am doing:
new_curves <- read.csv("new_curves_R.csv", as.is = TRUE)
g_range <- range(0,new_curves$X)
axis(2, las=1, at=4*0:g_range[2])
plot(new_curves$X1A.,new_curves$X,type="o", col="blue")
legend(1, g_range[2], c("new_curves$X1A."), cex=0.8, col=c("blue"));
title(xlab="Days", col.lab=rgb(0,0.5,0))
title(ylab="Total", col.lab=rgb(0,0.5,0))
However, this (obviously) only plots the first datapoint. (the legend is not working for some reason either). I am guessing I need some sort of for loop to add each Y value to the graph recursively. Likewise, a loop would be needed to make the legend.
thanks
dat <- read.table(text=", 1A+,2A+,3A-,3A+,5A-,5A+,6A-,6A+,7A-,7A+
6,4.530309305,5.520356001,3.437626731,5.146758132,,4.355022819,,4.191337618,,4.076583859
10,8.697814022,9.765817956,,9.636004092,3.725756716,8.600484774,3.457423715,8.358842335,2.246622784,7.244668991
12,,,8.176341701,,,,,,,
17,,,,,6.24785396,,5.077069513,,3.137524578", header=TRUE, sep=",", fill=TRUE)
matplot(dat[1], dat[-1])

Write x̄ (meaning average) in legend and how to prevent linebreak?

Good day!
I am not that familiar to R so I'd be glad to get a little help.
Assume I have the following minimal example:
test <- c(10,20,40,80,80)
avg <- mean(test)
avg <- format(avg,digits=2)
plot(test, xlab="x", ylab="y", pch = 4)
legend("topleft", legend= c("Average: ", avg))
I'd like to write x̄ instead of "average" - wonder if this is event possible as it's not a regular symbol - merely a combination of two (letter plus overline).
The other thing I'd like to get rid of is the line break after the word "Average (see arrow in graphic below):
There are two issues here. The first is that this is handled using ?plotmath in R. The operator you are looking for is bar(). This is not a function but markup that plotmath understands.
The second is that you need an expression in which avg is converted to its value. You need an expression because that is what plotmath works with. There are several solutions to this problem, but the one I use below is bquote(). You provide it an expression and anything wrapped in .( ) will be converted its value by evaluating the thing inside the .( ).
Here is your code and a suitably modified legend() call:
test <- c(10,20,40,80,80)
avg <- mean(test)
avg <- format(avg,digits=2)
plot(test, xlab="x", ylab="y", pch = 4)
legend("topleft", legend = bquote(bar(x)*":" ~ .(avg)))
Do note that this will insert exactly what is in avg. You may need to do
avg <- round(avg)
or some other formatting fix to get something nice and presentable.

In R, how to prevent blank page in pdf when using gridBase to embed subplot inside plot

As explained here, it is easy to embed a plot into an existing one thanks to gridBase, even though both plots use the base graphics system of R. However, when saving the whole figure into a pdf, the first page is always blank. How to prevent this?
Here is an example:
require(gridBase)
## generate dummy data
set.seed(1859)
x <- 1:100
y <- x + rnorm(100, sd=5)
ols <- lm(y ~ x)
pdf("test.pdf")
## draw the first plot
plot.new() # blank page also happens when using grid.newpage()
pushViewport(viewport())
plot(x, y)
## draw the second plot, embedded into the first one
pushViewport(viewport(x=.75,y=.35,width=.2,height=.2,just=c("center","center")))
par(plt=gridPLT(), new=TRUE)
hist(ols$residuals, main="", xlab="", ylab="")
popViewport(2)
dev.off()
I think it's a bit of a hack but setting onefile=FALSE worked on my machine:
pdf("test.pdf", onefile=FALSE)
In searching for an answer (which I didn't really find so much as stumbled upon in the forest) I came across this post to Rhelp from Paul Murrell who admits that mixing grid and base graphics is confusing even to the Master.
A work around solution I found was to initiate the pdf file inside the for loop; then insert an if clause to assess whether the first iteration is being run. When the current iteration is the first one, go ahead and create the output device using pdf(). Put the dev.off() after closing the for loop. An quick example follows:
for(i in 1:5){
if (i == 1) pdf(file = "test.pdf")
plot(rnorm(50, i, i), main = i)}
dev.off()

Resources