Sölvi Vignisson
Sölvi Vignisson

Reputation: 89

Sum of variables in a grouped barplot in ggplot2

I could not find an answer / a solution to the following question:

I have one numeric variable, number of chicks in a nest. I want to plot the sum of that variable in a grouped barplot for each month in a given year.

So y-axis is the number of chicks, x-axis are the years and the months are the fill.

Example dataframe:

df <- data.frame(matrix(ncol = 3, nrow = 8))
x <- c("year", "month","chicks")
colnames(df) <- x
df$year <- c(2010,2011,2012,2012,2012,2013,2013,2014)
df$month <- c(6,6,6,7,7,7,7,7)
df$chicks <- c(2,3,3,1,2,2,1,2)

This is how I would like the outcome to look like. It does not.

This is how I would like the outcome to look like. It does not

I believe I am missing how to sum the chicks for each month in a given year.

Upvotes: 2

Views: 2312

Answers (2)

koenniem
koenniem

Reputation: 576

I'm not sure how the rest of your (real) data looks, but this code normally works:

df %>% 
    ggplot(aes(x = year, y = chicks, fill = as.factor(month))) +
    geom_bar(stat = "identity", position = "dodge")

Edit: When extending your data I see what you want

set.seed(42)
df <- data.frame(matrix(ncol = 3, nrow = 100))
x <- c("year", "month","chicks")
colnames(df) <- x
df$year <- sample(2010:2014, 100, replace = T)
df$month <- sample(6:7, 100, replace = T) 
df$chicks <- sample(1:4, 100, replace = T)

So we first need to find the total number of chicks per month (per year), and then plot it using ggplot:

df %>% 
    group_by(year, month) %>% 
    summarise(summedChicks = sum(chicks)) %>% 
    ggplot(aes(x = year, y = summedChicks, fill = as.factor(month))) +
    geom_bar(stat = "identity", position = "dodge")

bar plot chicks

Upvotes: 3

S&#246;lvi Vignisson
S&#246;lvi Vignisson

Reputation: 89

I had help! I just needed to rearrange the dataframe.


df1 <- aggregate(chicks ~ year + month, data=df1, FUN= 'sum')

df1 %>% 
  ggplot(aes(x = year, y = chicks, fill = as.factor(month))) +
  geom_bar(stat = "identity", position = "dodge")

Upvotes: 1

Related Questions