Dal*_*nce 5 plot r ggplot2 r-grid
我试图显示几个变量的汇总每周数据的网格图.此图中最相关的两个组成部分是某个变量在给定周内所占的值的分布式汇总图(所以框图或小提琴图)以及累积在几周内的整数变量的累积计数图(所以a步骤图).我想将这两个图形绘制在一个对齐的x轴上grid
.我将用它ggplot2
来制作单独的图形,因为我迷上了Hadley Wickham(j/k,ggplot真的非常非常好).
问题是geom_boxplot
只需要x轴的因子而且只需要x轴的geom_step
连续数据.即使您使用coord_cartesian
或强制使用类似的x限制,这些也不一定对齐scale_x_...
.
我已经拼凑了一个hack使用geom_rect
它将适用于这个特定的应用程序,但如果,例如,我有一些其他因素导致一个星期多个框,这将是一个痛苦的适应.
强制性可重复性:
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"))
Run Code Online (Sandbox Code Playgroud)
和kludge:
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"))
Run Code Online (Sandbox Code Playgroud)
所以问题是:有没有办法强制geom_boxplot
连续轴或geom_step
因子轴?或者是否有其他实现,也许stat_summary
会更灵活一些,以便我可以对齐轴并且还可以轻松添加诸如分组颜色变量之类的东西?
一种方法是在设置了 的 x 轴上绘制两个图表factor(week)
,但在 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"))
Run Code Online (Sandbox Code Playgroud)