将基本图转换为grob,同时保持宽高比

时间:2018-10-30 19:47:48

标签: r ggplot2 cowplot grob

我需要将R基本图转换为grob,以便可以将其叠加在某些ggplot上。

我发现有两个用于执行此操作的功能,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

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分: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 package(v0.2.1)于2018-10-30创建

相关问题