Why aren't event.lines showing up when using chart.TimeSeries? - r

I am trying to plot various events over a times series data set using chart.TimeSeries in the PerformanceAnalytics library. I have tried to follow the example from but I think I am missing something.
ExampleChart MyChart
Neither my vertical event lines nor are my period areas are showing up on the chart. My code is almost identical to the example code. Any ideas?
risk.dates = c(
"2015-04-19"
)
risk.labels = c(
"Jon Oliver's Patent Episode "
)
cycle.dates <- c ("2015-1-01/2015-01-31",
"2015-03-01/2015-03-31",
"2015-05-01/2015-05-31",
"2015-07-01/2015-07-31"
)
chart.TimeSeries(df, colorset = "darkblue",
date.format.in = "%Y-%m-%d",
legend.loc = NULL,
period.areas = cycles.dates,
period.color = "lightblue",
event.lines = risk.dates,
event.labels = risk.labels,
event.color = "red", lwd = 2,
main = "Reddit Sentiment Index",
auto.grid = FALSE)
df <- data.frame(DateTime=
c("2/17/2015","2/18/2015","2/19/2015",
"2/20/2015","2/21/2015","2/22/2015",
"2/23/2015","2/24/2015","2/25/2015",
"2/26/2015","2/27/2015","2/28/2015",
"2/28/2015","2/27/2015"),
AvgSentimentScore=
c("NA","NA","NA","NA","NA","NA","NA","NA","NA",
"8.405975696","8.313470536","8.414560335",
"8.720865075","9.284902246"))

Related

twoord.plot axis changing

I am using twoord.plot for the first time, and I am having trouble getting the x axis set to years for a time-series data set. I have two different y-axes on different scales. Here is the code that I am working with.
#Install BatchGetSymbols
install.packages('BatchGetSymbols')
library(BatchGetSymbols)
#Get data from FRED
library(quantmod)
getSymbols('CPALTT01USM661S', src = 'FRED')
library(quantmod)
getSymbols('M2SL', src = 'FRED')
#Create data sets with equal number of observations
CPI = CPALTT01USM661S["1960-01-01/2019-01-01"]
M2 = M2SL["1960-01-01/2019-01-01"]
library(plotrix)
twoord.plot(rx = time(CPI), ry = CPI, lx = time(CPI), ly = M2,
main = "Money Supply and Prices",
xlim = NULL, lylim = NULL, rylim = NULL,
mar = c(5,4,4,4), lcol = "red", rcol = "blue", xlab = "", lytickpos = NA,
ylab = "M2", ylab.at = NA,
rytickpos = NA, rylab = "CPI", rylab.at = NA, lpch = 1,rpch = 2,
type = "l", xtickpos = NULL, xticklab = NULL,
halfwidth = 0.4, axislab.cex = 1, do.first = NULL)
Here is the graph that I am getting. Notice the x-axis is not in years.
The date values ( beginnings of each month) are in the index of the matrices, so to extract the year beginnings get every 12th item:
twoord.plot(rx=time(CPI), ry=CPI, lx=time(CPI),ly = M2, main="Money Supply and Prices",xlim=NULL,lylim=NULL,rylim=NULL,
mar=c(5,4,4,4),lcol="red",rcol="blue",xlab="",lytickpos=NA,ylab="M2",ylab.at=NA,
rytickpos=NA,rylab="CPI",rylab.at=NA,lpch=1,rpch=2,
type="l",
xtickpos=index(CPI)[seq(1,nrow(CPI), by=12)], #tick at year start
xticklab=format( index(CPI)[seq(1,nrow(CPI), by=12)], "%Y"), #just year
halfwidth=0.4, axislab.cex=1,
do.first=NULL, las=2) # not sure why las=2 didn't seem to work.

R igraph Format Date on axis

In the following igraph there are dates to be plotted as marks on the x-axis. Below I provided an example. As the dates are specified in the label matrix they are formatted into an atomic value. How do I get the dates on the x-axis to be displayed in a regular date format?
library(igraph)
nodes=data.frame(
c(0,1,2,3),
c("A","B","C","D")
)
colnames(nodes) = c("id","name")
links = data.frame(
c(0,0,1,2),
c(1,2,3,3)
)
colnames(links) = c("from","to")
layout = matrix(
c(as.Date('2010-01-01'),1, as.Date('2010-01-02'),1, as.Date('2010-01-02'),2, as.Date('2010-01-06'),1), byrow = TRUE, nrow=4
)
net = graph.data.frame(links, vertices = nodes)
plot.igraph(
net, xaxt="n",layout=layout,axes=TRUE,asp=0, rescale=FALSE,xlim=c(as.Date('2010-01-01'),as.Date('2010-01-06')),ylim=c(1,2)
)
You can replace the axis by your own values as explained here.
Using your code, it gives:
layout <- data.frame(Date = as.Date(c('2010-01-01','2010-01-02','2010-01-02','2010-01-06')), value = c(1,2,1,1))
plot.igraph(
net,
layout = layout,
rescale = FALSE,
axis = FALSE,
asp = 0,
xlim = as.Date(c('2010-01-01', '2010-01-06')),
ylim = c(1,2)
)
axis(1, at = as.numeric(layout$Date), labels = layout$Date, cex.axis = 0.9)
axis(2, at = 1:max(layout$value), labels = 1:max(layout$value))

turn off grid lines for R xyplot timeseries

I am plotting a time series with the timePlot function of the open air package of R. The graph has grey grid lines in the background that I would like to turn off but I do not find a way to do it. I would expect something simple such as grid = FALSE, but that is not the case. It appears to be rather complex, requiring the use of extra arguments which are passed to xyplot of the library lattice. I believe the answer lies some where in the par.settings function but all attempts have failed. Does anyone have any suggestions to this issue?
Here is by script:
timeozone <- import(i, date="date", date.format = "%m/%d/%Y", header=TRUE, na.strings="")
ROMO = timePlot(timeozone, pollutant = c("C7", "C9", "C10"), group = TRUE, stack = FALSE,y.relation = "same", date.breaks = 9, lty = c(1,2,3), lwd = c(2, 3, 3), fontsize = 15, cols = c("black", "black"), ylab = "Ozone (ppbv)")
panel = function(x, y) {
panel.grid(h = 0, v = 0)
panel.xyplot(x,y)
}

How to return a value if an error-free R function does not do so

My goal is to assign a plot produced by the pyramid package to a list. Later, I will have that plot and others inserted from the list into a document. But the pyramid function appears not to return a value. How can I assign the pyramid plot to an object?
install.packages("pyramid") # functions to draw a population pyramid
library(pyramid)
# create a mock data frame to comparing this plot to a counterpart from plotrix
df <- data.frame(level1 = c(9,9,4,3,34,28), levelsame = c(9,9,4,3,34,28),
title = c("Dir", "Exec. Dir", "Mgr", "Sr. Mgr", "Mgt Princ", "EVP+"))
# assign the plot (hopefully) to an object
empty <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> empty
NULL
Likewise, if I assign the pyramid call to my list, nothing happens. There is no value for the list returned by pyramid.
plotlist2[["pyramid"]] <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> plotlist2[1]
[[1]]
NULL
I fear I am blundering in some obvious mis-understanding, so I welcome being set aright. Thank you.
You can use the recordPlot() function to save the current plot to a variable.
In your case you could do:
#print the plot
pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
#save the current printed plot
pyrPlot<-recordPlot()
#plot it again
pyrPlot
You might have to enable the displaylist using dev.control(displaylist ="enable") for this to work depending on the graphical device you are using

How to change the color and width of lines with par function in R

I have a question about the par function in R.
I want to change the color and/or width of a line in a graph with par function. (I am using par function because the gaps.plot command below does not allow "col" option to be included. The gaps.plot command is used after the synth command).
So, I used the following command. But I noticed that the lines of the BOX are changed rather than the lines of the GRAPHS.
synth1<-read.csv(file="C:\\Users\\Research\\R\\synthinR_v4.csv",header=TRUE)
attach(synth1)
library("Synth")
dataprep.out34 <- dataprep(foo = synth1, predictors = c("lncdsales", "md1", "md2","md3", "md4", "md5", "md6", "md7", "md8", "md9", "md10", "md11", "yd1", "yd2", "yd3", "yd4", "yd5", "yd6", "yd7", "yd8"), predictors.op = "mean", time.predictors.prior = -13:1, dependent = "lndigital", unit.variable = "artistalbumcode", time.variable = "release", treatment.identifier = 34, controls.identifier = c(1:33, 35:49), time.optimize.ssr = -13:1, time.plot = -13:25)
synth.out34 <- synth(data.prep.obj = dataprep.out34, method = "BFGS")
par(lwd = 2, col="#cccccc")
gaps.plot(synth.res = synth.out34, dataprep.res = dataprep.out34, Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) , Main = NA)
Does anyone know how to fix this problem??
Thank you in advance for your willingness to help. I greatly appreciate it!
The col argument to par sets the default plotting colour (i.e. when col is not explicitly specified in plotting calls), but unfortunately col = "black" is hard-coded into the source of gaps.plot.
You can make a modified copy of the function by either (1) viewing the source (F2 in RStudio, or just executing gaps.plot), editing it and assigning it to a new object, or (2) doing something like the following:
gaps.plot2 <- eval(parse(text=gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot))))
and then using gaps.plot2 as you would use gaps.plot:
gaps.plot2(synth.res = synth.out34, dataprep.res = dataprep.out34,
Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) ,
Main = NA)
Alter the lwd similarly. For example to make lines red and have width of 3, use nested gsub calls like this:
gaps.plot2 <- eval(parse(text=gsub('lwd = 2', 'lwd = 3',
gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot)))))

Resources