Curious G.
Curious G.

Reputation: 877

How to insert the difference between two bars ggplot2

I did this code:

    ggplot(data = df, aes(x = sex,y = weight, fill=sex))+
  geom_bar(position="dodge", stat="summary",width = 0.3) +theme_classic() +
  scale_y_continuous(breaks = round(seq(min(0), max(400), by = 50), digits=2),limits=c(0,400)) +
  labs(x = element_blank(),y="Weight (kg)") + 
  labs( title= "Weight") + 
  scale_fill_manual(values = c("red", "black")) +
  theme (plot.title=element_text( hjust=0.5, vjust=0.5, face='bold'),axis.text.x=element_text(size = 10),axis.text.y=element_text(size = 9),
         axis.title.y = element_text(size = 12),legend.position = "none",
         axis.title.x = element_text(size = 12))

and I obtained this plot:

enter image description here

But I would like to insert the difference between these two bars, like or similar to this:

enter image description here

I used this dataset:

set.seed(1234)
top <- data.frame(
  sex=factor(rep(c("Male","Female"), each=200)),
  weight=round(c(rnorm(200, mean=350, sd=5),
                 rnorm(200, mean=300, sd=5)))
)

Upvotes: 1

Views: 958

Answers (1)

heds1
heds1

Reputation: 3438

This isn't exactly what you want, but it's an option. We can calculate the means using aggregate, find the difference between the two values, then put that as a geom_text label on top of a new geom_bar with a lower alpha.

set.seed(1234)
df <- data.frame(
  sex=factor(rep(c("Male","Female"), each=200)),
  weight=round(c(rnorm(200, mean=350, sd=5),
             rnorm(200, mean=300, sd=5))))


gender_means <- aggregate(df$weight, by=list(df$sex), mean)
mean_difference <- gender_means[[2]][[2]] - gender_means[[2]][[1]]

ggplot(data = df, aes(x = sex,y = weight, fill=sex))+
    geom_bar(position="dodge", stat="summary",width = 0.3) +theme_classic() +
    scale_y_continuous(breaks = round(seq(min(0), max(400), by = 50), digits=2),limits=c(0,400)) +
    labs(x = element_blank(),y="Weight (kg)") + 
    labs( title= "Weight") + 
    scale_fill_manual(values = c("red", "black")) +
    theme (plot.title=element_text( hjust=0.5, vjust=0.5, face='bold'),axis.text.x=element_text(size = 10),axis.text.y=element_text(size = 9), axis.title.y = element_text(size = 12),legend.position = "none", axis.title.x = element_text(size = 12)) + 
    geom_bar(aes(x=sex,y=gender_means[[2]][[2]]),stat="identity",alpha=0.5,width=0.3) + 
    geom_text(aes(x=sex,y=gender_means[[2]][[2]],label=ifelse(sex=="Female",paste0("Difference = ",mean_difference," kg"),"")), vjust=2.2, size=3.4)

graph

Upvotes: 2

Related Questions