Ggplot2: select chart area

I work with some time series data and would like to highlight the area of ​​the graph when certain conditions are met. For instance:

require(ggplot2) require(quantmod) initDate <- "1993-01-31" endDate <- "2012-08-10" symbols <- c("SPY") getSymbols(symbols, from=initDate, to=endDate, index.class=c("POSIXt","POSIXct")) spy<-SPY$SPY.Adjusted spy$sma<-SMA(spy$SPY.Adjusted,200) spy<-spy[-(1:199),] spy<-as.data.frame(spy) ggplot(spy,aes(x=index(spy),y=spy$SPY.Adjusted))+geom_line()+geom_line(aes(x=index(spy),y=spy$sma)) 

The above code displays the data, but how can I highlight a section when it is ever close, above sma? This question is similar to How to highlight time ranges on a chart? but then this guide. Is there a function in ggplot2 for conditional building?

+6
source share
1 answer

Based on the code in the TA.R quantmod file, here is the code that rle uses to find the beginning and end of the rectangles.

 runs <- rle(as.logical(spy[, 1] > spy[, 2])) l <- list(start=cumsum(runs$length)[which(runs$values)] - runs$length[which(runs$values)] + 1, end=cumsum(runs$lengths)[which(runs$values)]) rect <- data.frame(xmin=l$start, xmax=l$end, ymin=-Inf, ymax=Inf) 

Combine this with some ggplot2 code from the accepted answer to the question you were contacting:

 ggplot(spy,aes(x=index(spy),y=spy$SPY.Adjusted))+geom_line()+geom_line(aes(x=index(spy),y=spy$sma))+geom_rect(data=rect, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), color="grey20", alpha=0.5, inherit.aes = FALSE) 

And you will get:

enter image description here

If you cancel the build order and use alpha=1 in geom_rect , it may (or may not look) more like you:

 ggplot(spy,aes(x=index(spy),y=spy$SPY.Adjusted))+geom_rect(data=rect, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), border=NA, color="grey20", alpha=1, inherit.aes = FALSE)+geom_line()+geom_line(aes(x=index(spy),y=spy$sma)) 

enter image description here


Since you have an xts object. You cannot even convert to data.frame . Here's how you could build it using the new plot.xts method in the xtsExtra package, created by Michael Weilandd as part of the Google Summer Code project

 spy <- as.xts(spy) require(xtsExtra) plot(spy, screens=1, blocks=list(start.time=paste(index(spy)[l$start]), end.time=paste(index(spy)[l$end]), col='lightblue'), legend.loc='bottomright', auto.legend=TRUE) 

enter image description here

+13
source

Source: https://habr.com/ru/post/923811/


All Articles