【发布时间】:2016-01-13 15:43:45
【问题描述】:
我尝试在使用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)
编辑:
我刚刚发现这似乎是stat_summary() 的问题。当我使用另一个几何/图层时,限制将保持在原始图中。另一个例子:
plot2 = ggplot(data = ChickWeight, aes(x = Time, y = weight, color = Diet)) +
geom_jitter()
plot2
plot2 + annotation_custom(sum_table)
【问题讨论】:
-
我不确定这个问题,但我不认为这是
stat_summary的问题,如果你这样做plot2+stat_summary(fun.data = "mean_cl_boot", size = 1, alpha = .5)+annotation_custom(sum_table)那么你的 ylim 会被保留。 -
这很有趣。它设置整个数据范围的 y 限制,而不是
geom = 'pointrange'(stat_summary默认使用)。因此,如果我没看错的话,在我的第一个示例中,ylim 会调整为汇总和显示值的范围(来自pointrange),但是当添加annotation_custom时,它会再次使用整个数据的范围。