如何将 ggplot 与 chartSeries 结合使用

问题描述

让我们看一些由 ggplot 创建的人为情节:

ggplot()+aes(x  = 1:100,y = 1:100) + geom_line() 

enter image description here

另外让我们考虑由 chartSeries 创建的烛台图:

start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL",src = "yahoo",from = start,to = end)
chartSeries(AAPL)

enter image description here

我的问题是:如何并排绘制它们 - plot_grid() 包中的函数 cowplotggplot 对象所做的事情。我检查过,plot_grid() 无法并排绘制它们,因为 chartSeries 不是 ggplot 对象。那么有什么办法可以将它们彼此相邻绘制?

解决方法

chartSeries 的结果是一个 chob。这不能通过 cowplot 转换为 grob。

为了得到你想要的东西,你可以使用 tidyquant 的函数。这将股票数据作为 tibble / data.frame 返回,并且它有一些函数可以在 ggplot2 中绘制所有内容。有关更多选项,请参阅 the vignette。然后,您可以将所有内容与 cowplot 或 patchwork 包结合起来。我只展示拼凑而成的结果。但是牛图看起来是一样的,只是去掉了标题和说明。

library(tidyquant)
library(ggplot2)
aapl <- tq_get("AAPL",from = start,to = end)
aapl_plot <- aapl %>% 
  ggplot(aes(x = date,y = close)) + 
  geom_candlestick(aes(open = open,high = high,low = low,close = close))


g <- ggplot() +aes(x = 1:100,y = 1:100) + geom_line() 

#combine with cowplot
cowplot::plot_grid(g,aapl_plot)

# combine with patchwork
library(patchwork)
g + aapl_plot + plot_annotation('This is a title',caption = 'made with patchwork')

enter image description here