arvchi
arvchi

Reputation: 61

Failure with geom_line: arguments imply differing number of rows

I am trying to add a "significance bar" to my barplot, just as presented here: https://stackoverflow.com/a/29263992/9188785.

However, when I try to re-produce it on my data, I get the following error: ... arguments imply differing number of rows: 6, 0.

Note that everything works as long as I don't include the geom_line in the end.

Data and code

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

Upvotes: 0

Views: 946

Answers (1)

pogibas
pogibas

Reputation: 28339

You have to move fill from the main ggplot() function to geom_bar as fill aesthetics doesn't work with 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"))

enter image description here

Upvotes: 2

Related Questions