【问题标题】:Annotations that work in ggplot2 3.1.1 fail in 3.2.1. How to fix?在 ggplot2 3.1.1 中工作的注释在 3.2.1 中失败。怎么修?
【发布时间】:2020-01-07 00:22:36
【问题描述】:

我的代码在 ggplot2 3.1.1 的多面直方图中进行自定义注释在运行 ggplot2 3.2.1 的另一台计算机上失败,抛出此错误: 错误:美学必须是长度 1 或与数据相同 (9):标签

如何使我的注释出现在 ggplot2 3.2.1 中制作的构面中?

下面是使用 mtcars 的最小示例。

谢谢!!

library(ggplot2, warn.conflicts = FALSE)
library(dplyr, warn.conflicts = FALSE)

lb <- mtcars %>%
      group_by(cyl) %>%
      summarize(n=n(), avg_gear=round(mean(gear),1))
lb$label <- paste0("n=",lb$n, "     avg_gear=",lb$avg_gear)
print(lb)

ggplot(data=mtcars, aes(x=gear)) +
geom_histogram(binwidth=1) +
facet_grid(. ~ cyl) +
annotate("text", x=4, y=13, label=lb$label) +  
ggtitle("histograms of gear, faceted by cyl") 

【问题讨论】:

    标签: r ggplot2 annotate facet-grid


    【解决方案1】:

    你可以使用另一个层:

    ggplot(data=mtcars, aes(x=gear)) +
      geom_histogram(binwidth=1) +
      facet_grid(. ~ cyl) +
      geom_text(data = lb, aes(x = 4, y = 13, label = label)) +    # in place of annotate
      ggtitle("histograms of gear, faceted by cyl") 
    

    【讨论】:

    • 非常感谢乔恩·斯普林。
    • 乔恩,您的解决方案不适用于我的实际代码。我的最小案例有点太小了?我的实际代码也为直方图着色。以下适用于注释掉的第 4 行且没有注释,但是当我取消注释并尝试注释时失败。非常感谢任何帮助。我宁愿不必恢复到 ggplot2 3.1.1。 ggplot(data=mtcars, aes(x=gear, group=carb, fill=carb)) + geom_histogram(binwidth=1) + facet_grid(. ~ cyl) + geom_text(data = lb, aes(x = 4, y = 13, label = label)) + ggtitle("齿轮直方图,cyl刻面,carb着色")
    • lb 有 carb 列吗?如果没有,您可能希望将 aes() 的那部分预先从全局调用中移出并移入 geom_histogram 层。
    • 该技术适用于我的生产代码。再次感谢您。
    猜你喜欢
    • 2017-03-20
    • 2011-12-19
    • 2016-10-27
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2020-04-22
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多