【问题标题】:Error in FUN(X[[i]], ...) : object not found when adding geom_text with facetFUN(X[[i]], ...) 中的错误:添加带有 facet 的 geom_text 时找不到对象
【发布时间】:2019-01-21 04:04:13
【问题描述】:

添加 geom_text(data = dat_text, mapping = aes(x , y , label = label)) 行给了我以下错误: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

【问题讨论】:

    标签: r facet facet-wrap geom-text


    【解决方案1】:

    您需要合并您的 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))
    

    FUN(X[[i]], ...) 中的错误:找不到对象“物种”

    这行得通:

    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))
    

    【讨论】:

    • 太棒了。是的,我使用 left_join 将 label 、 x 和 y 列添加到我的大数据集中,一切正常