ggplot2 несколько сюжетов, с общей легендой, одним цветом фона, 1 основным и 3 подзаголовками и нестандартным макетом - PullRequest
0 голосов
/ 10 июня 2018

Я пытаюсь создать график, который будет представлять собой комбинацию из 6 графиков, созданных в ggplot2.Условия:

  1. Один основной заголовок
  2. Три субтитра
  3. Общий цвет фона
  4. Различные размеры сюжетов
  5. Одна легендавнизу

И это должно выглядеть примерно так: Desired plot

Я нашел биты и кусочки, но я не знаю, как их поставитьсовмещены.

Для добавления основного заголовка я использовал Поместите заголовок панели мультиплота с помощью ggplot2

layout <- matrix(c(1, 1, 2, 3, 3, 4), nrow = 2, byrow = TRUE)
grid.arrange(A, B, C, D, top = "Title",
             layout_matrix = layout)

Plot with grid.arrange

Iнашли функцию multiplot (http://www.cookbook -r.com / Graphs / Multiple_graphs_on_one_page_ (ggplot2) / ) и позволяют дозировать несколько графиков с разными размерами, но другие требования не выполняются

plot_list <- list(A, B, C, D)
layout <- matrix(c(1, 1, 2, 3, 3, 4), nrow = 2, byrow = TRUE)
multiplot(plotlist = plot_list, layout = layout) 

Plot with multiplot

Я также нашел, как создать общую легенду, но размеры диаграмм одинаковы ( Добавить общую легенду для комбинированных ggplots )

grid_arrange_shared_legend <- function(...) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lheight <- sum(legend$height)
  grid.arrange(
    do.call(arrangeGrob, lapply(plots, function(x)
      x + theme(legend.position="none"))),
    legend,
    ncol = 1,
    heights = unit.c(unit(1, "npc") - lheight, lheight))
}

grid_arrange_shared_legend(A, B, C, D)

Plot with grid_arrange_shared_legend

пример данных

DF <- data.frame(ID = 1:10, Pop = (1:10)^2, gr = c("A", rep("B", 8), "A"))
DF_Pie <- DF %>%
  group_by(gr) %>%
  summarise(Years = n(),
            Pop_Years = sum(Pop))

A <-  ggplot(DF, aes(x = ID, col = gr, fill = gr)) +
  geom_bar()+ 
  theme(legend.position="none")

B <- ggplot(DF_Pie, aes(x = factor(1), y = Years, fill = gr))+
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0)+ 
  theme(legend.position="none")

C <- ggplot(DF, aes(x = ID, y = Pop, col = gr, fill = gr)) +
  geom_bar(stat="identity") +
  theme(legend.position="bottom")

D <- ggplot(DF_Pie, aes(x = factor(1), y = Pop_Years, fill = gr))+
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) + 
  theme(legend.position="none")

РЕДАКТИРОВАТЬ

Благодаря @ hpesoj626 я знаюкак сделать все, но условие 3 все еще применяется - общий цвет фона Chart after hpesoj626  changes

РЕДАКТИРОВАТЬ 2

Я создал следующую диаграмму end result но пространство между сюжетами и заголовками огромно

1 Ответ

0 голосов
/ 10 июня 2018

Из связанного поста есть решение ggpubr.Я посмотрел на пакет и увидел ggpubr::anotate_figure, который, кажется, способен делать то, что вы хотите.Я немного поработал с графиками A, B, C, D.

A <-  ggplot(DF, aes(x = ID, col = gr, fill = gr)) +
  geom_bar() + 
  xlab(NULL) + theme(legend.position = "none")

B <- ggplot(DF_Pie, aes(x = factor(1), y = Years, fill = gr))+
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) +  labs(x = NULL, y = NULL) + theme(legend.position = "none")

C <- ggplot(DF, aes(x = ID, y = Pop, col = gr, fill = gr)) +
  geom_bar(stat="identity")  

D <- ggplot(DF_Pie, aes(x = factor(1), y = Pop_Years, fill = gr))+
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) +  labs(x = NULL, y = NULL)


p1 <- ggarrange(A, B, ncol=2) 
p2 <- ggarrange(C, D, ncol=2, common.legend = TRUE, legend = "bottom") 

p1 <- annotate_figure(p1, top = text_grob("According to years"))
p2 <- annotate_figure(p2, top = text_grob("According to population"))

p <- ggarrange(p1, p2, nrow=2, common.legend = TRUE, legend="bottom", heights = c(3,3.75)) 
annotate_figure(p, top = text_grob("Main title", face = "bold", size = 16))

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...