4

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

我发现有几个功能可以做到这一点,ggplotify::as.grob并且cowplot::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

任何人都可以帮忙吗?谢谢!

4

1 回答 1

2

这在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 包(v0.2.1)于 2018 年 10 月 30 日创建

于 2018-10-31T01:34:36.257 回答