使用 facet_wrap 时无法向 geom_text 添加条件

Can't add criteria to geom_text when using facet_wrap

我正在尝试使用 ggplot2 在 r 中创建一个图形,我使用 facet_wrap 为不同类型的设置复制 3 组堆叠条形图。但是,当我使用 geom_text 仅标记大于 1.5 的值时,我收到此错误:

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(1L, 1L, 1L, 1L,  : 
  replacement has 24 rows, data has 16

请指教

这是我的图形代码:

ggplot(data, aes(x = year, y = percent, fill = facility,label = round(percent))) + geom_bar(aes(y = percent, x = year, fill = facility), 
           data = data,stat="identity") +
  geom_line(aes(x=year, y =percent),linetype="dashed",color="black", position = 'stack',data = data)+
  geom_text(data = subset(data,percent>1.5),size = 3, position = position_stack(vjust = 0.5),color="white")+
  theme(legend.position="bottom", legend.direction="horizontal",
        legend.title = element_blank()) +
  scale_y_continuous(labels = dollar_format(suffix = "%", prefix = "")) +
  scale_x_continuous(breaks=0:1,
                     labels=c("2010","2015"))+
  labs(x="", y="Percentage") +
  ggtitle("Year comparison") +
  coord_flip()+
  theme(plot.title = element_text(size=20,face="bold",hjust = 0.5))+
  facet_wrap(~data$type, ncol = 1, scales = "free")

Here is the image... I'm basically trying to get rid of the label 0 in the picture

谢谢!!!

当您执行 facet_wrap() 时,您将包括原始数据框中的 "type" (data$type) 的完整列,大概有 24 行长。您想使用像 facet_wrap(~ type) 这样的形式来允许 ggplot2 使用分面的动态数据。

有点难以解释,但在示例数据中可能很容易玩弄。

不行

library(tidyverse)
iris %>%
  ggplot(aes(Sepal.Length, Sepal.Width, label = Species)) +
  geom_point() +
  geom_text(data = subset(iris, Sepal.Length > 6)) +
  facet_wrap(~ iris$Species)
#> Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = structure(c(1L, 1L, : replacement has 150 rows, data has 61

会起作用

iris %>%
  ggplot(aes(Sepal.Length, Sepal.Width, label = Species)) +
  geom_point() +
  geom_text(data = subset(iris, Sepal.Length > 6)) +
  facet_wrap(~ Species)