我尝试在用ggplot2::ggplot()
创建的图表中添加一个小表格。该表通过gridExtra::tableGrob()
添加到保存的ggplot对象。使用gridExtra和annotation_custom()向ggplot添加表格会改变y轴限制
我的问题是,这似乎改变了我原来的阴谋的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()
的问题。当我使用另一个geom/layer时,这些限制保持原样。对于另一个例子:
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被保存。 – George
这很有趣。它为整个数据范围设置y限制,而不是来自'geom ='pointrange''(默认情况下使用'stat_summary')。所以,如果我看到了这一点,在我的第一个例子中,ylim被调整到汇总值和显示值的范围(来自'pointrange'),但是当添加'annotation_custom'时,它会再次使用整个数据的范围。 – abel