【问题标题】:ggplot2: highlight chart areaggplot2:突出显示图表区域
【发布时间】:2012-08-21 11:03:42
【问题描述】:

我正在处理一些时间序列数据,并希望在某些条件成立时突出显示图表区域。例如:

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))

上面的代码绘制了数据,但是当 close 高于 sma 时,如何突出显示该部分?这个问题类似于How to highlight time ranges on a plot?,但它是手动的。 ggplot2中是否有条件绘图功能?

【问题讨论】:

  • 您链接到的问题 这样做的方法。 ggplot2 尚不具备理解 geom_shade_the_region_that_I_have_in_mind_you_know_that_one() 之类的功能。您必须实际告诉它您想要阴影的区域。
  • 如果您放入适当的库调用以指示运行该代码需要哪些包,您将增加让非量化人员试验您的代码的机会。
  • @joran 非常感谢您有见地的回答~会努力想出一些有用的东西。
  • 不过,我应该补充一点,当然可以使用链接问题中的技术来编写一个返回所需geom_rect 对象的函数。但是您仍然必须自己“手动”编写该函数。

标签: r ggplot2 xts quantmod


【解决方案1】:

基于quantmod 包的TA.R 文件中的代码,这里是使用rle 查找矩形起点和终点的代码。

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)

将它与来自accepted answer 的一些ggplot2 代码结合到您链接到的问题:

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)

你会得到:

如果您颠倒绘图顺序并在geom_rect 中使用alpha=1,它可能(或可能不会)看起来更像您想要的:

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))


因为你有一个xts 对象。您甚至可能不想转换为data.frame。以下是您如何使用 Michael Weylandt 创建的 xtsExtra 包中全新的 plot.xts 方法绘制它,作为 Google Summer of 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多