Преобразование базового сюжета в grob с сохранением соотношения сторон

Мне нужно преобразовать базовый график R в гроб, чтобы его можно было наложить на некоторые 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

Кто-нибудь может помочь? Спасибо!


person Bob    schedule 30.10.2018    source источник


Ответы (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)

Создано 30 октября 2018 г. с помощью пакета reprex (v0.2.1)

person Claus Wilke    schedule 31.10.2018
comment
Ага - исправлено! Спасибо! Я замечаю, что они все еще немного смещены от центра, но это значительное улучшение. - person Bob; 01.11.2018