如何结合 ggplot 和 chartSeries

How to combine ggplot with chartSeries

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

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

并且让我们考虑由 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)

我的问题是:如何并排绘制它们 - cowplot 包中的函数 plot_grid()ggplot 对象的作用。我检查了 plot_grid() 将无法并排绘制它们,因为 chartSeries 不是 ggplot 对象。那么有什么办法可以将它们并排绘制吗?

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

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

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