My legend in r is not showing. What could be the issue? - r

This is my code, it works so far, except that the legend does not appear in the plot:
plot(norm_prices_daily[,1], col = "blue",lwd=3,grid.col = NA, ylim = c(0,3))
lines(norm_prices_daily[,2],lwd=3, col = "dark green")
legend("bottomright",legend=c("Stock 1","Stock 2"),col = c("blue","dark green"))
norm_prices_daily is a zoo object with two columns and 182 rows.
Here is part of the data. Output from dput(head(norm_prices_daily[,1],20)):
structure(c(1, 0.9929401294387, 0.99644855697716, 0.9936552740678,
0.998526620668352, 1.00517207744161, 1.00230213170477, 1.00929440707496,
1.00776579745506, 1.0096505179963, 1.01809781273736, 1.02202987149226,
1.01931947115634, 1.01961413204347, 1.0207774879027, 1.01154745364837,
0.99563509229331, 1.0056447937894, 1.00477302623885, 1.00792234548049
), class = c("xts", "zoo"), .indexCLASS = "Date", .indexTZ = "UTC", tclass = "Date", tzone = "UTC", src = "yahoo", updated = structure(1600533381.35332, class = c("POSIXct",
"POSIXt")), index = structure(c(1577923200, 1578009600, 1578268800,
1578355200, 1578441600, 1578528000, 1578614400, 1578873600, 1578960000,
1579046400, 1579132800, 1579219200, 1579564800, 1579651200, 1579737600,
1579824000, 1580083200, 1580169600, 1580256000, 1580342400), tzone = "UTC", tclass = "Date"), .Dim = c(20L,
1L), .Dimnames = list(NULL, "^GSPC"))
I have tried different options for the position of the legend, such as specific x and y coordinates, because I suspected that the legend is there but just too low or something. But that does not seem to the issue.

You haven't specified the kind of line you want in the legend, but it should still print the labels. Here is a slight modification of the first example on the manual page for print.zoo to make it more comparable to yours:
x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-"))
set.seed(42)
x <- zoo(cbind(rnorm(5), rnorm(5, sd= 0.2)), x.Date)
plot(x[, 1], col = "blue")
lines(x[, 2], col = "dark green")
legend("bottomright", legend=c("Stock 1","Stock 2"), lty=1, col = c("blue","dark green"))

Related

I cannot figure out why my dates don't work

structure(list(Position = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Date = structure(c(1685750400, 1685750400, 1685750400, 1685750400, 1685750400, 1685750400, 1685750400, 1685750400, 1685750400, 1685750400), tzone = "UTC", class = c("POSIXct", "POSIXt")), Time
= structure(c(-2209017523, -2209017518, -2209017513, -2209017508, -2209017503, -2209017498, -2209017493, -2209017488, -2209017483, -2209017478), tzone = "UTC", class = c("POSIXct", "POSIXt")), DateTime = structure(c(1685808077, 1685808082, 1685808087,
1685808092, 1685808097, 1685808102, 1685808107, 1685808112, 1685808117, 1685808122), tzone = "UTC", class = c("POSIXct", "POSIXt")), Temperatuur = c(21.2, 21.2, 21.6, 21.7, 22, 22.2, 20.1, 20.2, 20.3, 20.3), Treatment = c("Tempex", "Tempex", "Tempex",
"Tempex", "Tempex", "Tempex", "Tempex", "Tempex", "Tempex", "Tempex")), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))
My R code:
time.start=as.POSIXct("2023-06-03, 16:00",format="%H:%M")
time.end=as.POSIXct("2023-07-03, 07:30",format="%H:%M")
ggplot(logger, aes(DateTime, Temperatuur, color = Treatment))+
geom_line(size = 1)+
scale_x_datetime(limits = c(time.start, time.end),
breaks = date_breaks("24 hours"),
labels = date_format("%H:%M"))
I just cannot figure out why I am getting this: plot
Can someone please help me?
I tried to follow advice online, but that got me nowhere. Changing from 24 to 12 hours also didn't help. Maybe it's a problem in my excel file, but that all seems alright.
If we remove the commas from the time.* strings and fix the errant format=, it should work.
time.start <- as.POSIXct("2023-06-03 16:00")
time.end <- as.POSIXct("2023-07-03 07:30")
ggplot(logger, aes(DateTime, Temperatuur, color = Treatment)) +
geom_line(size = 1) +
scale_x_datetime(
limits = c(time.start, time.end),
breaks = date_breaks("24 hours"),
labels = date_format("%H:%M"))
I think perhaps you are confounding the use of labels=date_format("%H:%M") as what you think time.start/time.end should be (or how they should look), which is incorrect. Since the x-axis is (I'm inferring) a POSIXt object, then the time.* objects also must be the same object. You don't need to make them "look" (i.e., "%H:%M") the same as how you want the axis labels rendered, it is handled automatically by ggplot.

R xlab and ylab in xts plot

Plotting an xts should be really easy, but I can't seem to get the xlab, and ylab to work..
ylab="Price"
xlab="Date"
plot(x = basket[, 1], lty="dotted", xlab = xlab, ylab = ylab, col = "mediumblue", lwd = 2)
title("Cumulative")
This will plot the figure, but without any labels on the x- and y-axis.
There must be an easy solution to this. The plot looks as it should besides that issue. I have tried with xts.plot, zoo.plot, xyplot but none seem to do the trick.
Data sample
structure(c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073,
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889,
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567,
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013,
1.04571606282071), class = c("xts", "zoo"), index = structure(c(946944000,
947030400, 947116800, 947203200, 947462400), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
NULL, c("new.close", "new.close.1", "new.close.2", "new.close.3"
)))
It is plot.zoo, not zoo.plot. These all work for me:
library(xts)
plot(as.zoo(basket[, 1]), xlab = "X", ylab = "Y")
plot.zoo(basket[, 1], xlab = "X", ylab = "Y")
library(lattice)
xyplot(basket[, 1], xlab = "X", ylab = "Y")
library(ggplot2)
autoplot(basket[, 1]) + xlab("X") + ylab("Y")
Note
basket <-
structure(c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073,
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889,
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567,
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013,
1.04571606282071), class = c("xts", "zoo"), index = structure(c(946944000,
947030400, 947116800, 947203200, 947462400), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
NULL, c("new.close", "new.close.1", "new.close.2", "new.close.3"
)))
I know this might not be exactly what you had in mind, but it gets the job done. Plus, you get to work with ggplot2 which way better than the standard plotting system. In addition, I am using ggfortify which extends ggplot() capabilities to handle time series.
library(xts)
library(zoo)
library(ggfortify)
library(ggplot2)
myts = structure(
c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073,
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889,
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567,
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013,
1.04571606282071),
class = c("xts", "zoo"),
index = structure(c(946944000, 947030400,
947116800, 947203200,
947462400),
tzone = "UTC",
tclass = "Date"),
.Dim = 5:4, .Dimnames = list(NULL,
c("new.close",
"new.close.1",
"new.close.2",
"new.close.3" ) )
)
autoplot( myts[ , 1], xlab = "Date", ylab = "Price" )
Created on 2020-05-05 by the reprex package (v0.3.0)

Side by side plots for PerformanceAnalytics in R

The following script plots 2 charts side by side:
require(xts)
par(mfrow=c(1,2))
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))
XTS2 <- XTS1 ^ 0.2
plot(XTS1)
plot(XTS2)
The following script fails to plot 2 charts side by side:
require(PerformanceAnalytics)
require(xts)
par(mfrow=c(1,2))
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))
XTS2 <- XTS1 ^ 0.2
charts.PerformanceSummary(XTS1)
charts.PerformanceSummary(XTS2)
Would anyone know how to get the latter script to plot 2 charts side by side?
I would like to avoid using another package if possible. Thanks.
chart.PerformanceSummary is really just a wrapper to several charts.
You could do this, and extend it to any number of symbols horizontally if you wish (more than 2 symbols if you wanted):
par(mfrow=c(3,2))
# First row
chart.CumReturns(XTS1, ylab = "Cumulative Return", main = "give me a title")
chart.CumReturns(XTS2, ylab = "Cumulative Return", main = "give me a title2")
# second row
chart.BarVaR(XTS1)
chart.BarVaR(XTS2)
# third row
chart.Drawdown(XTS1, main = "DD title", ylab = "Drawdown",
)
chart.Drawdown(XTS2, main = "", ylab = "Drawdown",
)
You need to add the appropriate parameters to each plot for things like colour and titles (leaving that to you), but you have the flexibility of adding any charts from the wonderful xts, quantmod, performanceAnalytics packages (and others).

Identify a bar of interest on an OHLC chart on the graph itself

I have calculations that identify bar location of events; my calculation output is the number of a bar within my time series or its index (I can work with either). The issue I have is that when I have more than 50 bars on the chart I have to count the bars to identify the bar of interest.
Is there a way to put some kind of an "indicator" on the chart itself for the bars of interest based on the calculation I have?
Say my program indicated bar 3 is a bar of interest. Are there any tricks that would help in identifying that bar graphically on the chart with an arrow or a dot or anything really to avoid having to count the bars. I realize the time is usually on the x axes, but when the chart has many bars you can't read the time and date off the chart, and even if you did its hard to be sure they are aligned properly.
I provided an OHLC AAPL data for 5 minute bars bellow as a dput():
would like to be able to tell R "when you chart my data please identify bar #3 on the chart"
I usually use chartSeries() of the quantmod package to create my charts, but I am open to using other functions.
dput(AAPL)
structure(c(266, 265.95, 265.93, 265.89, 265.91, 266, 266, 265.96,
265.97, 265.98, 265.93, 265.9, 265.84, 265.86, 265.8625, 265.97,
265.96, 265.89, 265.875, 265.98), .Dim = c(5L, 4L), .Dimnames = list(
NULL, c("Open", "High", "Low", "Close")), index = structure(c(1299962039,
1299962098, 1299962157, 1299962219, 1299962278), tzone = "", tclass = c("POSIXct",
"POSIXt")), tclass = c("POSIXct", "POSIXt"), tzone = "", .indexCLASS = c("POSIXct",
"POSIXt"), .indexTZ = "", class = c("xts", "zoo"))
chartSeries(AAPL) would create an OHLC bar chart with 5 bars.
AAPL <- structure(c(266, 265.95, 265.93, 265.89, 265.91, 266, 266, 265.96,
265.97, 265.98, 265.93, 265.9, 265.84, 265.86, 265.8625, 265.97,
265.96, 265.89, 265.875, 265.98), .Dim = c(5L, 4L),
.Dimnames = list(NULL, c("Open", "High", "Low", "Close")),
index = structure(c(1299962039, 1299962098, 1299962157, 1299962219, 1299962278),
tzone = "", tclass = c("POSIXct", "POSIXt")),
tclass = c("POSIXct", "POSIXt"), tzone = "",
.indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", class = c("xts", "zoo"))
chartSeries(AAPL)
addLines(v=3)
addPoints(3, Cl(AAPL)[3])

Move x-axis labels down from x-axis

x<- structure(list(count = c(4259120, 4317840, 4444000, 4254240,
4656800), the_date = structure(c(1389589200, 1389675600, 1389762000,
1389848400, 1389934800), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("count",
"the_date"), row.names = c(51L, 406L, 664L, 197L, 196L), class = "data.frame")
par(mar = c(8, 4, 4, 2) + 0.1)
plot(x$the_date, x$count, type="l", xaxt = "n", xlab = "")
axis(1, labels = FALSE)
labels<-x$the_date
labels<-format(labels, format="%b-%d-%Y")
text(x$the_date, par("usr")[3] - 0.75, srt = 55, adj = 1, labels = labels, xpd = TRUE)
I've tried adjusting the par("usr")[3] - 0.75 offset as specified here, but the labels aren't moving at all.
You can a trick like this using 2 calls to axis functions. I am using here axis.Date since you deal with dates(better for formatting). Then you can ply with line argument t play with labels positions.
axis(1,labels=FALSE)
axis.Date(1,at = x$the_date,las=2, format= "%m-%d",line=0.5,tick=FALSE)

Resources