【问题标题】:How to combine ggplot with chartSeries如何将ggplot与chartSeries结合起来
【发布时间】:2021-01-02 13:32:51
【问题描述】:

让我们来看看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 对象。那么有什么办法可以将它们彼此相邻绘制?

【问题讨论】:

    标签: r ggplot2 quantmod


    【解决方案1】:

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

    要得到你想要的,你可以使用 tidyquant 的函数。这会将股票数据返回为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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-02
      • 2017-05-22
      • 2018-12-08
      • 2012-03-17
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多