I want to create a bar graph with an x-axis (length in cm) in groups. What I have is a dataset with 400 individuals and their body lengths. This is a really basic graph but I have trouble finding the correct R commands. (I do not want to create a histogram.) Here is a dummy dataset.
length = c(6,6,7,8,9,10,11,12,13,14,15,16,17,18,19,19,20,20,21,21,23,24,26,27,29,30,31,38,34,35,30,48,50)
How do I create a bar graph with counts as categories on the x-axis? For example; a count from 5 cm – 10 cm is 6, a count from 10 cm – 15 cm is 5, etc.
CodePudding user response:
library(ggplot2)
library(dplyr)
df <- data.frame(length = c(6,6,7,8,9,10,11,12,13,14,15,16,17,18,19,19,20,20,21,21,23,24,26,27,29,30,31,38,34,35,30,48,50))
plot_df <- df %>%
mutate(length_bin = cut(length, c(seq(min(length), max(length) 5, by=5)), right = F, include.lowest = T))
levels(plot_df$length_bin) <- gsub("\\[|\\]|\\(|\\)", "", levels(plot_df$length_bin))
levels(plot_df$length_bin) <- gsub(",", "-", levels(plot_df$length_bin))
plot_df %>%
group_by(length_bin) %>%
summarise(count = n()) %>%
ggplot(aes(length_bin, count)) geom_col()