【问题标题】:Adding a table to ggplot with gridExtra and annotation_custom() changes y-axis limits使用 gridExtra 和 annotation_custom() 将表添加到 ggplot 会更改 y 轴限制
【发布时间】: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 时,它会再次使用整个数据的范围。

标签: r ggplot2 gridextra


【解决方案1】:

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

顺便说一句,这两个图不会给出完全相同的 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

回想一下,ggplot 直到绘制时间才评估函数 - 每次绘制 p1 或 p2 时,都会选择一个新的引导样本。

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多