abe*_*bel 6 r ggplot2 gridextra
我尝试在我创建的图中添加一个小摘要表ggplot2::ggplot().该表将添加gridExtra::tableGrob()到已保存的ggplot对象.
我的问题是,这似乎改变了我原始情节的y限制.有没有办法避免这种情况而不必再通过指定限制ylim()?
以下是使用ChickWeight数据集的问题的最小示例:
# load packages
require(ggplot2)
require(gridExtra)
# create plot
plot1 = ggplot(data = ChickWeight, aes(x = Time, y = weight, color = Diet)) +
stat_summary(fun.data = "mean_cl_boot", size = 1, alpha = .5)
plot1
# create table to add to the plot
sum_table = aggregate(ChickWeight$weight,
by=list(ChickWeight$Diet),
FUN = mean)
names(sum_table) = c('Diet', 'Mean')
sum_table = tableGrob(sum_table)
# insert table into plot
plot1 + annotation_custom(sum_table)
Run Code Online (Sandbox Code Playgroud)
编辑:
我只是发现它似乎是一个问题stat_summary().当我使用另一个geom/layer时,限制将保持原始图中的限制.另一个例子:
plot2 = ggplot(data = ChickWeight, aes(x = Time, y = weight, color = Diet)) +
geom_jitter()
plot2
plot2 + annotation_custom(sum_table)
Run Code Online (Sandbox Code Playgroud)
plot1 的 y 范围与 plot2 不同,原因是annotation_custom它从原始aes语句中获取美学,而不是stat_summary(). 要使两个图的 y 范围相同(或大致相同 - 见下文),请停止annotation_custom从原始数据中获取其美感。也就是说,aes()在stat_summary().
# load packages
require(ggplot2)
require(gridExtra)
# create plot
plot1 = ggplot(data = ChickWeight) +
stat_summary(aes(x = Time, y = weight, color = Diet), fun.data = "mean_cl_boot", size = 1, alpha = .5)
plot1
# create table to add to the plot
sum_table = aggregate(ChickWeight$weight,
by=list(ChickWeight$Diet),
FUN = mean)
names(sum_table) = c('Diet', 'Mean')
sum_table = tableGrob(sum_table)
# insert table into plot
plot2 = plot1 + annotation_custom(sum_table, xmin = 10, xmax = 10, ymin = 200, ymax = 200)
plot2
Run Code Online (Sandbox Code Playgroud)
顺便说一下,这两个图不会给出完全相同的 y 范围的原因是因为stat_summary(). 事实上,重复绘制 p1,您可能会注意到 y 范围的细微变化。或者检查构建数据中的 y 范围。
编辑更新到 ggplot2 ver 3.0.0
ggplot_build(plot1)$layout$panel_params[[1]]$y.range
ggplot_build(plot2)$layout$panel_params[[1]]$y.range
Run Code Online (Sandbox Code Playgroud)
回想一下 ggplot 在绘制时间之前不会评估函数 - 每次绘制 p1 或 p2 时,都会选择一个新的引导样本。