将基础图转换为grob,保持纵横比

4
我需要将一个R基础绘图转换为grob,以便可以覆盖在一些ggplot之上。我发现了一些实现这个目的的函数,包括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

有人可以帮忙吗?谢谢!

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)

创建于2018年10月30日,使用reprex package(版本为v0.2.1)


好的 - 已经修复了!谢谢!我注意到它们仍然有点偏离中心,但是已经大大改善了。 - Bob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接