FUN(X[[i]], ...) 中的错误:使用 facet 添加 geom_text 时找不到对象

Error in FUN(X[[i]], ...) : object not found when adding geom_text with facet

添加 geom_text(数据 = dat_text, 映射 = aes(x , y , 标签 = 标签)) 行给我以下错误:FUN(X[[i]], ...) 错误:找不到对象 'sex'。这无关紧要,我不知道该怎么办。

没有最后一行,ggplot 生成的图形就很好。

dat_text <- data.frame(
  label = c("Most unisex year", "Marion Jones wins gold in Olympic", "Jackie Robinson to major leauge", "Jamie Hunter Cartwright appears on Bonanza", "The Little Mermaid sways Ariel towards girls"),
  cyl   = c("Jessie", "Marion", "Jackie", "Jamie", "Ariel"),
  x     = c(1940, 1940, 1940,1940, 1940),
  y     = c(.3, .4, .2,.2,.3))

# make the plot here
data.babyname.all %>% 
  ggplot( mapping = aes(x = year, y = perc, fill = sex)) +
  geom_density(stat = "identity", position = "stack" , show.legend = F ) +
  scale_fill_manual(values = c('#E1AEA1','#9ABACF'))  + 
  geom_point(data = most.unisex.year.and.value, mapping = aes(x =  year, y = perc), 
             size = 3, 
             fill = "white", 
             color = "black", 
             shape = 21) +
  facet_wrap(~name, ncol= 7, nrow=5) +
  theme_minimal() + #set theme
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.border = element_blank(),
        text = element_text(size = 12),
        panel.grid = element_blank(),
        axis.title.x= element_blank(),
        axis.title.y=element_blank(),
        plot.background = element_blank(),
        axis.ticks.x = element_line(color = "black"),
        axis.ticks.length = unit(0.1, "cm")) + 
  scale_y_continuous(breaks = c(0,.50,1), labels= c("0%", "50%","%100")) +
  scale_x_continuous(breaks = c(1940, 1960, 1980,2000), labels= c('1940', "'60","'80",'2000')) +
  geom_text(data = dat_text, mapping = aes(x , y , label = label)) 

image of what I get without the last line

您需要合并 data.frame 个对象。这是重现错误的方法:

library(dplyr)
library(ggplot2)
mylabels<-names(mtcars)
iris %>% 
  ggplot(aes(Species,fill=Species))+geom_bar()+
  geom_text(data = mtcars,aes(mpg,disp,label=mylabels))

Error in FUN(X[[i]], ...) : object 'Species' not found

这个有效:

iris1<-iris1[1:11,]
iris1 %>% 
mutate(label.s=mylabels) %>% 
  ggplot(aes(Petal.Length,Sepal.Length,col=Species))+geom_point()+
  geom_text(aes(label=label.s))