2016-01-13 47 views
6

我尝试在用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) 

ylim problem with annotation_custom()

编辑: 我想通了,这似乎是与stat_summary()的问题。当我使用另一个geom/layer时,这些限制保持原样。对于另一个例子:

plot2 = ggplot(data = ChickWeight, aes(x = Time, y = weight, color = Diet)) + 
     geom_jitter() 
plot2 
plot2 + annotation_custom(sum_table) 

ylim problem with annotation_custom()

+0

我不确定这个问题,但我不认为这是一个'stat_summary'的问题,它是'plot2 + stat_summary(fun.data =“mean_cl_boot”,size = 1,alpha = .5) + annotation_custom(sum_table)'然后你的ylim被保存。 – George

+0

这很有趣。它为整个数据范围设置y限制,而不是来自'geom ='pointrange''(默认情况下使用'stat_summary')。所以,如果我看到了这一点,在我的第一个例子中,ylim被调整到汇总值和显示值的范围(来自'pointrange'),但是当添加'annotation_custom'时,它会再次使用整个数据的范围。 – abel

回答

4

的y范围为plot1是从plot2不同,作为原因,annotation_custom采取它的美学从原始aes声明,而不是由stat_summary()所使用的修改的数据帧。要使两个图的y范围相同(或大致相同 - 请参阅下文),请停止annotation_custom从原始数据中获得其美学效果。即在stat_summary()内移动aes()

# 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 

enter image description here

顺便说一句,这两个地块将不会给出确切相同的Y范围的原因是因为在stat_summary()引导功能。事实上,反复绘制p1,你可能会注意到y范围的轻微变化。或者检查构建数据中的y范围。

ggplot_build(plot1)$layout$panel_ranges[[1]]$y.range 
ggplot_build(plot2)$layout$panel_ranges[[1]]$y.range 

回想ggplot不评估功能,直到绘制时间 - 每次P1或P2被绘制时,一个新的自举样本被选择。