Выровняйте график по разным осям, используя Cowplot - PullRequest
1 голос
/ 04 марта 2020

Я пытаюсь выровнять три графика (с разными масштабами по оси Y) по левой оси Y. Другими словами, я хотел бы, чтобы красная ось была выровнена:

enter image description here

Однако ось Y первого графика не совпадает с Ось Y нижнего левого графика.

Код

# Libraries
library(tidyverse)
library(cowplot)

df1 <- data.frame(x = seq(0, 100, 1), 
                  y = seq(100, 0, -1))

df2 <- data.frame(x = seq(0, 10, 0.1), 
                  y = seq(1, 10^9, length.out = 101 ) )

p1 <- ggplot(data = df1) + 
  geom_line(aes(x = x, y = y))

p2 <- ggplot(data = df2) + 
  geom_line(aes(x = x, y = y))

combi_p2 <- plot_grid(p2, p2, nrow = 1)
plot_grid(p1, combi_p2, ncol = 1, axis = "l", align = "v")

Попытка исправить это

Используя предоставленную информацию здесь , Я переписал последнюю часть кода:

require(grid)                    # for unit.pmax()
p1 <- ggplotGrob(p1)             # convert to gtable
combi_p2 <- ggplotGrob(combi_p2) # convert to gtable

p1.widths <- p1$widths[1:3]      # extract the first three widths, 
                                 # corresponding to left margin, y lab, and y axis
combi_p2.widths <- combi_p2$widths[1:3]                 # same for combi_p2 plot
max.widths <- unit.pmax(p1.widths, combi_p2.widths)     # calculate maximum widths
p1$widths[1:3] <- max.widths                            # assign max. widths to p1 gtable
combi_p2$widths[1:3] <- max.widths                      # assign max widths to combi_p2 gtable

# plot_grid() can work directly with gtables, so this works
plot_grid(p1, combi_p2, labels = "AUTO", ncol = 1)

К сожалению, я не смог исправить выравнивание:

enter image description here

Вопрос

Как мне выровнять ось Y верхнего графика с левым нижним графиком, используя диаграмму в R?

Ответы [ 2 ]

1 голос
/ 04 марта 2020

A cowplot решение Клауса О. Вилке представлено здесь .

Он основан на функции align_plot, которая сначала выравнивает верхний график по левому нижнему графику вдоль оси y. Затем выровненные графики передаются в функцию plot_grid.

# Libraries
library(tidyverse)
library(cowplot)

df1 <- data.frame(x = seq(0, 100, 1), 
                  y = seq(100, 0, -1))

df2 <- data.frame(x = seq(0, 10, 0.1), 
                  y = seq(1, 10^9, length.out = 101 ) )

p1 <- ggplot(data = df1) + 
  geom_line(aes(x = x, y = y))

p2 <- ggplot(data = df2) + 
  geom_line(aes(x = x, y = y))

plots <- align_plots(p1, p2, align = 'v', axis = 'l')
bottom_row <- plot_grid(plots[[2]], p2, nrow = 1)

plot_grid(plots[[1]], bottom_row, ncol = 1)

enter image description here

1 голос
/ 04 марта 2020

Я думаю, что вы можете использовать ggplotGrob и соединить их с gtable_rbind и gtable_cbind. Наконец, вы можете нарисовать график с помощью grid.draw()

df1 <- data.frame(x = seq(0, 100, 1), 
              y = seq(100, 0, -1))
df2 <- data.frame(x = seq(0, 10, 0.1), 
              y = seq(1, 10^9, length.out = 101 ) )
p1 <- ggplot(data = df1) + 
              geom_line(aes(x = x, y = y))
p2 <- ggplot(data = df2) + 
              geom_line(aes(x = x, y = y))

g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)

frame_g2 <- gtable_frame(g2 , debug = TRUE)

frame_combi <- gtable_frame(gtable_cbind(frame_g2,frame_g2),
                            width = unit(2, "null"),
                            height = unit(1, "null"))
frame_g1  <-
   gtable_frame(
     g1,
     width = unit(1, "null"),
     height = unit(1, "null"),
     debug = TRUE
    )

 grid.newpage()
 all_frames <- gtable_rbind(frame_g1, frame_combi)
 grid.draw(all_frames)

И так выглядит график. enter image description here

...