hema
hema

Reputation: 735

How to add bar to each group to represent group mean?

I am interested in adding a bar to each group (species) to represent each group average. For example, in the below example, I have four separate groups, I would like to add another bar to each group to represent each group average.
thank you

   library(ggplot2)

   # create a dataset
   specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) ,       rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
head(data)

  # Grouped
  ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="dodge", stat="identity")

Upvotes: 0

Views: 64

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

What you’re looking for is called a summary statistic (stat_summary in ggplot2 parlance).

And rather than another bar, I suggest adding a new geometry that’s less ambiguous. A dot is conventional, or a short horizontal bar.

Here’s a minimal code to add it:

ggplot(data, aes(fill = condition, x = specie, y = value)) +
    geom_col(position = 'dodge') +
    stat_summary(aes(group = specie), fun.y = mean, geom = 'point')

(Note that I’ve used geom_col() instead of geom_bar(stat = 'identity').)

Upvotes: 1

utubun
utubun

Reputation: 4520

I would do it this way:

library(tidyverse)

dat %>%
  group_by(species) %>%
  summarise(conditions = 'average', values = mean(values)) %>%
  bind_rows(dat) %>%
  ggplot(aes(x = species, y = values, fill = conditions)) + 
  geom_col(position = "dodge") +
  ggthemes::theme_tufte() +
  scale_fill_brewer(palette = 'Set2')

plot

Data

set.seed(57377888)
dat <- data.frame(
  species   = c(
    rep("sorgho" , 3),
    rep("poacee" , 3),
    rep("banana" , 3),
    rep("triticum" , 3)
    ),
  conditions = rep(c('normal', 'stress', 'nitrogen'), 4),
  values     = abs(rnorm(12, 0, 15)),
  stringsAsFactors = F
)

Upvotes: 1

Related Questions