使用 ggplot2 和网格对齐离散轴和连续轴

Align discrete and continuous axes with ggplot2 and grid

我正在尝试显示几个变量每周汇总数据的网格图。该图最相关的两个组成部分是特定变量在给定一周内所取值的分布摘要图(箱线图或小提琴图)和整数变量在数周内累积的累积计数图(因此步骤图)。我想使用 grid 在对齐的 x 轴上绘制这两个图。我将使用 ggplot2 来制作单独的图表,因为我迷恋 Hadley Wickham(j/k,ggplot 非常非常好)。

问题是geom_boxplot只取x轴的因数,而geom_step只取x轴的连续数据。即使您使用 coord_cartesianscale_x_....

强制使用类似的 x 限制,这些也不一定对齐

我已经使用 geom_rect 拼凑了一个 hack,它适用于这个特定的应用程序,但是如果我有一些其他因素会导致多个框,那么适应起来会很痛苦一个星期。

强制复制:

library(ggplot2)
library(grid)

var1 <- data.frame(val = rnorm(300),
                   week = c(rep(25, 100), 
                        rep(26, 100), 
                        rep(27, 100))
                  )

var2 <- data.frame(cumul = cumsum(c(0, rpois(2, 15))),
                   week = c(25, 26, 27)
                  )


g1   <- ggplot(var1, aes(x = factor(week), y = val)) + 
  geom_boxplot()

g2   <- ggplot(var2, aes(x = week, y = cumul)) + 
  geom_step() + scale_x_continuous(breaks = 25:27)

grid.newpage()
grid.draw(rbind(ggplotGrob(g1),
                ggplotGrob(g2),
                size = "last"))

和拼凑:

library(dplyr)

chiggity_check <- var1 %>% 
  group_by(week) %>% 
  summarise(week.avg = mean(val),
            week.25  = quantile(val)[2],
            week.75  = quantile(val)[4],
            week.05  = quantile(val)[1],
            week.95  = quantile(val)[5])

riggity_rect <- ggplot(chiggity_check) +
  geom_rect(aes(xmin = week - 0.25, xmax = week + 0.25,
                ymin = week.25,
                ymax = week.75)) +
  geom_segment(aes(x = week - 0.25, xend = week + 0.25,
                   y = week.avg, yend=week.avg),
               color = "white") +
  geom_segment(aes(x = week, xend = week ,
                   y = week.25, yend=week.05)) +
  geom_segment(aes(x = week, xend = week ,
                   y = week.75, yend=week.95)) +
  coord_cartesian(c(24.5,27.5)) +
  scale_x_continuous(breaks = 25:27)

grid.newpage()
grid.draw(rbind(ggplotGrob(riggity_rect),
                ggplotGrob(g2 + coord_cartesian(c(24.5,27.5))),
                size = "last"))

所以问题 is/are:有没有办法强制 geom_boxplot 到连续轴或 geom_step 到因子轴?或者是否有其他一些实现,也许 stat_summary 会更灵活一些,以便我可以对齐轴并可能轻松添加诸如分组颜色变量之类的东西?

一种方法是在 factor(week) 设置的 x 轴上绘制两个图表,但在 g2 图(阶梯图)中,在 geom_blank() 中绘制,以便比例尺为设置。然后在 geom_step() 中,按数字标度绘制:as.numeric(factor(week))

library(ggplot2)
library(grid)

# Your data
var1 <- data.frame(val = rnorm(300),
                   week = c(rep(25, 100), 
                        rep(26, 100), 
                        rep(27, 100))
                  )

var2 <- data.frame(cumul = cumsum(c(0, rpois(2, 15))),
                   week = c(25, 26, 27)
                  )

# Your g1
g1   <- ggplot(var1, aes(x = factor(week), y = val)) + 
  geom_boxplot()

# Modified g2
g2   <- ggplot(var2) + geom_blank(aes(x = factor(week), y = cumul)) +
geom_step(aes(x = as.numeric(as.factor(week)), y = cumul)) 

grid.newpage()
grid.draw(gridExtra::rbind.gtable(ggplotGrob(g1),
                ggplotGrob(g2),
                size = "last"))