[英]Align x axis with grid.arrange
我正在嘗試繪制兩個對齊的圖形,但是其中一個具有標簽,而其中一個沒有標簽。
例:
library(dplyr)
library(ggplot2)
df <-
seq(as.Date("2019-01-01"), as.Date("2019-01-31"), by = 1) %>%
as_tibble() %>%
rename(day = value) %>%
mutate(
x = seq(1, 31, by = 1),
y = x * 2 - 20
)
p1 <-
df %>%
gather(key, value, c(x, y)) %>%
ggplot(aes(x = day, y = value, color = key)) +
geom_line(size = 1)
p2 <-
df %>%
ggplot(aes(x = day, y = y / x)) +
geom_line(size = 1)
grid.arrange(
p1, p2
)
結果:
有沒有一種方法可以不使用facet_wrap來對齊軸? (我想為每個圖添加特定的標簽格式化程序,因為它們位於不同的單位,而facet_wrap不允許我這樣做)
您可以使用cowplot
套件將它們作為具有相同圖例的不同地塊進行管理:
library(cowplot)
legend <- get_legend(p1) # get the legend of the first one plot
# here the plots in a grid
prow <- plot_grid( p1 + theme(legend.position="none"),
# here you add the percentage
p2 + theme(legend.position="none")+ scale_y_continuous(labels = scales::percent),
align = 'v',
labels = c("A", "B"),
hjust = -1,
nrow = 2)
# here you add the legend
p <- plot_grid( prow, legend, rel_widths = c(3, .3))
p
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.