【问题标题】:Convert base plot to grob, keeping aspect ratio将基本图转换为 grob,保持纵横比
【发布时间】:2019-04-03 22:35:09
【问题描述】:

我需要将一个 R 基础图转换为一个 grob,所以它可以叠加在一些 ggplots 上。

我发现有几个函数可以做到这一点,ggplotify::as.grobcowplot::plot_to_gtable。问题是,它们不保留原始基图的纵横比。由于有问题的基础图是使用circlize 包绘制的圆圈,因此我需要保留纵横比,否则不可能始终叠加在 ggplots 上。

这里有一些示例代码来展示我在做什么:

library(circlize)
library(cowplot)

tst <- function() {
  df <- data.frame(
    sector = factor(letters), 
    label = letters
  )
  circos.clear()
  circos.initialize(df$sector, xlim=c(-1.0, 1.0), sector.width=1)
  circos.trackPlotRegion(factors=df$sector,
                         y=rep(1.0, length(df$sector)),
                         ylim=c(0, 1.0))

  circos.trackText(df$sector, 
                   x=rep(0, nrow(df)), y=rep(0, nrow(df)),
                   facing="bending", niceFacing = T,
                   labels=df$label)
}

# Run tst() now and see a nice circle
tst()
# If you resize your view window, it will always be redrawn as a circle

agrob <- cowplot::plot_to_gtable(tst)
ggdraw(agrob)
# But this produces an oval, that is redrawn to different proportions when the window is resized

plt <- data.frame(group = c('a', 'b', 'c'), sizes = c(.3, .4, .3)) %>%
   ggplot(aes(x=group, y = sizes, fill=group)) +
   geom_bar(stat='identity', width=1) + 
   coord_polar("x") +
   guides(fill=FALSE)


ggdraw(plt) + draw_plot(agrob)
# And here you see the problem in superimposing the circle over the ggplot

有人可以帮忙吗?谢谢!

【问题讨论】:

    标签: r ggplot2 cowplot grob


    【解决方案1】:

    这在cowplot的开发版本中得到了解决。如果你想混合基础图形和网格图形,你应该更新。

    library(circlize)
    library(cowplot) # devtools::install_github("wilkelab/cowplot")
    library(dplyr)
    library(ggplot2)
    
    tst <- function() {
      df <- data.frame(
        sector = factor(letters), 
        label = letters
      )
      circos.clear()
      circos.initialize(df$sector, xlim=c(-1.0, 1.0), sector.width=1)
      circos.trackPlotRegion(factors=df$sector,
                             y=rep(1.0, length(df$sector)),
                             ylim=c(0, 1.0))
    
      circos.trackText(df$sector, 
                       x=rep(0, nrow(df)), y=rep(0, nrow(df)),
                       facing="bending", niceFacing = T,
                       labels=df$label)
    }
    
    # Run tst() now and see a nice circle
    tst()
    

    # cowplot::as_grob() produces the exact same result
    
    agrob <- cowplot::as_grob(tst)
    ggdraw(agrob)
    

    plt <- data.frame(group = c('a', 'b', 'c'), sizes = c(.3, .4, .3)) %>%
      ggplot(aes(x=group, y = sizes, fill=group)) +
      geom_bar(stat='identity', width=1) + 
      coord_polar("x") +
      guides(fill=FALSE)
    
    ggdraw(plt) + draw_plot(agrob)
    

    reprex package (v0.2.1) 于 2018 年 10 月 30 日创建

    【讨论】:

    • 是的 - 已修复!谢谢!我注意到它们仍然稍微偏离中心,但有很大的改进。
    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 2012-08-25
    • 2013-08-24
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2015-09-04
    • 2013-03-04
    相关资源
    最近更新 更多