我在三个站点收集了数据,在每个站点中,这些数据都为多个受试者收集了多次。
数据如下所示:
set.seed(1)
df <- data.frame(site = c(rep("AA",1000),rep("BB",500),rep("CC",750)),
y = c(rnorm(1000,1,2),runif(500,1,3),rgamma(750,shape=1)))
#add subjects - using a function that randomly generates
#a number of subjects that adds up to their total at that site
site_a_subjects <- diff(c(0, sort(20*sample(19)), 1000))
site_b_subjects <- diff(c(0, sort(30*sample(9)), 500))
site_c_subjects <- diff(c(0, sort(40*sample(4)), 750))
#add these subjects
df$site_subjects <- c(unlist(sapply(1:20, function(x) rep(letters[x], site_a_subjects[x]))),
unlist(sapply(1:10, function(x) rep(letters[x], site_b_subjects[x]))),
unlist(sapply(1:5, function(x) rep(letters[x], site_c_subjects[x]))))
我想绘制y
每个站点的直方图。这条ggplot2
简单的线很容易实现:
ggplot(df, aes(x=y)) + geom_histogram(colour="black", fill="white") + facet_grid(. ~ site)
但是,我还想在每个站点直方图上绘制一个子图,它是该站点上每个主题观察次数的直方图。像添加:
hist(table(df$site_subjects[which(df$site == "AA")]))
hist(table(df$site_subjects[which(df$site == "BB")]))
hist(table(df$site_subjects[which(df$site == "CC")]))
分别到三个站点直方图。
知道怎么做吗?
我想知道是否annotation_custom
可以调整以实现这一目标?
此代码将起作用,但前提是:
ggplotGrob(ggplot(df, aes(x=site_subjects)) + geom_bar() + theme_bw(base_size=9))
command 可以接受一个对象或类似list
的ggplot
东西。
这是'几乎; 解决方案:首先弄清楚所有方面直方图中的最大条高度是多少
ymax <- max(sapply(unique(df$site), function(x) max(hist(df$y[which(df$site == x)],plot=FALSE)$counts)))
然后:
main.plot <- ggplot(df, aes(x=y)) + geom_histogram(colour="black", fill="gray") + facet_grid(~site) + scale_y_continuous(limits=c(0,1.2*ymax))
main.plot.info <- ggplot_build(main.plot)
xmin <- min(main.plot.info$data[[1]]$x[which(main.plot.info$data[[1]]$PANEL == 1)])
xmax <- max(main.plot.info$data[[1]]$x[which(main.plot.info$data[[1]]$PANEL == 1)])
main.plot <- main.plot + annotation_custom(grob = grid::roundrectGrob(),xmin = xmin, xmax = xmax, ymin=ymax, ymax=1.2*ymax)
sub.plot <- ggplotGrob(ggplot(df, aes(x=site_subjects)) + geom_bar() + theme_bw(base_size=9))
combined.plot <- main.plot + annotation_custom(grob = sub.plot, xmin = xmin, xmax = xmax, ymin=ymax, ymax=1.2*ymax)