在ggplot2 3.1.1中起作用的注释在3.2.1中失败。如何解决?

问题描述 投票:0回答:1

我的代码在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个回答
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") 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.