【问题标题】:Failure with geom_line: arguments imply differing number of rowsgeom_line 失败:参数暗示不同的行数
【发布时间】:2018-07-22 17:45:39
【问题描述】:

我正在尝试在我的条形图中添加一个“意义栏”,如下所示:https://stackoverflow.com/a/29263992/9188785

但是,当我尝试在我的数据上重新生成它时,我收到以下错误:... arguments imply differing number of rows: 6, 0

请注意,只要我最后不包含 geom_line,一切正常。

数据和代码

# Data
          means            cat
1         296.1610            A
2         235.9618            B
3         220.6905            C
4         127.2546            D

# Df for the new line
df1 <- data.frame(a = c(1, 1:4,4), b = c(349, 350, 350, 350, 350, 349))

# Plot
library(ggplot2)    

p1<-ggplot(df,aes(y=means,x=cat,fill=cat))
p1 + geom_bar(stat="Identity",width = 0.75) 
+ labs(y="Mean") 
+ geom_errorbar(aes(ymin=means-sd,ymax=means+sd),width=.2,position = position_dodge(.9)) 
+ theme(legend.position = "none", axis.text.x=element_text(family = "Arial",size=16, face = "bold"),axis.title.x=element_blank(), axis.title.y=element_text(family = "Arial",size=16,face = "bold"),axis.text.y=element_text(family = "Arial",size=14,face = "bold"), legend.title=element_blank()) 
+ scale_fill_grey(start = 0.4,end = 0.8) 
+ geom_line(data = df1, aes(x = a, y = b)) + annotate("text", x = 2, y = 350, label = "*", size = 8)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您必须将fill 从主要的ggplot() 函数移动到geom_bar,因为fill 美学不适用于geom_line

    # Using dummy sd as not specified
    sd <- 10
    
    library(ggplot2)
    ggplot(df, aes(cat, means)) +
        geom_bar(aes(fill = cat), stat = "Identity", width = 0.75) +
        geom_errorbar(aes(ymin = means - sd, ymax = means + sd),
                      width = 0.2, position = position_dodge(0.9)) +
        geom_line(data = df1, aes(a, b)) + 
        annotate("text", x = 2, y = 350, label = "*", size = 8) +
        scale_fill_grey(start = 0.4, end = 0.8) +
        labs(y = "Mean",
             fill = NULL) +
        theme(legend.position = "none", 
              axis.text.y = element_text(family = "Arial",size=14,face = "bold"), 
              axis.text.x = element_text(family = "Arial", size = 16, face = "bold"), 
              axis.title.x = element_blank(), 
              axis.title.y = element_text(family = "Arial",size = 16, face = "bold"))
    

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 2019-02-13
      • 2015-12-08
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多