I am trying to add some text to the right hand side of a ggplot which has a date as the x axis but I am having problems setting the annotation_custom
xmin and xmax parameters for a Date object. I would be grateful for some help with this.
library(ggplot2)
library(quantmod)
getSymbols("SPY", from="2013-11-01", to=Sys.Date())
SPY = data.frame(SPY)
SPY$Date = as.Date(rownames(SPY))
colnames(SPY)[6] = 'Price'
tail(SPY)
gg1 <- ggplot(data=SPY, aes(x=Date, y=Price)) + geom_line() + theme_bw()
gg1 <- gg1+ theme(plot.margin = unit(c(0.1,6,0.1,0.1), "cm"))
gg1
Text1 = textGrob("xxxxxxxxxxxxxxxxxxxxxxxxxxx")
Text1
ymax1 <- max((SPY)[6])
ymin1 <- min((SPY)[6])
xmin1 <- tail(SPY$Date,1)
xmax1 <- tail(SPY$Date,1)+10
gg1 <- gg1 + annotation_custom(grob = Text1,
xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1)
gg1 <- ggplot_gtable(ggplot_build(gg1))
gg1$layout$clip[gg1$layout$name=="panel"] <- "off"
grid.draw(gg1)
Error in Ops.Date((x - from[1]), diff(from)) :
/ not defined for "Date" objects
Error in UseMethod("grid.draw") :
no applicable method for 'grid.draw' applied to an object of class "c('gg', 'ggplot')"
Change the line
gg1 + annotation_custom(grob = Text1,
xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1)
to
gg1 + annotation_custom(grob = Text1,
xmin = as.numeric(xmin1), xmax = as.numeric(xmax1),
ymin = as.numeric(ymin1), ymax = as.numeric(ymax1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With