ggplot2 barplot of sums?

Hi!

I want to show my data in barplots using ggplot2 but the bars won't sum. The data consists of observations of number of plant stems of five different species in five different streams at six points in time.

This is my code:
ggplot(data,aes(fill=Stream,x=Tn,y=No_stems))+geom_bar(position="dodge",stat="identity") + ggtitle("Number of stems per stream over time")

The Help tab in R studio writes the following about bar charts:
There are two types of bar charts: geom_bar() and geom_col(). geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead. geom_bar() uses stat_count() by default: it counts the number of cases at each x position. geom_col() uses stat_identity(): it leaves the data as is.

I have tried to use geom_col() in stead of geom_bar() but it changes nothing - my bars are still far too low and I suspect that the bars represent a single observation (or a mean) in stead of the sum of observations for all five species in each stream. What am I doing wrong? I want to illustrate how the number of stems in each stream develops over time...

There's two things going on, I think you want to use the stat "count" (the default for geom_bar) and then use a weight of "No_stems". Here's some made up data I used to demonstrate.

library(tidyverse)

# The data consists of observations of number of plant stems of five different
# species in five different streams at six points in time.
data <- tibble(Tn=rep(1:6, each=25),
               Stream=rep(rep(1:5, each=5), 6),
               No_stems=rpois(150, 10)) %>%
  mutate(Stream=as.factor(Stream))

ggplot(data,aes(fill=Stream,x=Tn,weight=No_stems))+
  geom_bar(position="dodge") + 
  ggtitle("Number of stems per stream over time")

Created on 2020-05-11 by the reprex package (v0.3.0)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.