user8848543
user8848543

Reputation: 65

ggplot with categorical bins in R

I need to plot a bar plot using ggplot x-axis that shows the bins (e.g. 300-310, 310-320, 320-330 etc) and counts of "CAT" column each category in y-axis.

I am totally new to ggplot. Can somebody help me to achieve this using ggplot.?

Thanks in advance.

Table:

YEAR    ID     Sep_wk1  Sep_wk2  Sep_wk3  Sep_wk4   Sep_wk5  CAT
1998   40015   300.05   310.11   320.65   301.25    315.82   0
1998   32014   310.25   315.85   330.25   350.25    341.56   1
1998   56525   315.56   355.25   410.85   411.25    450.25   1
1998   45012   400.65   325.23   300.25   356.25    311.25   0

Upvotes: 2

Views: 457

Answers (1)

Pete
Pete

Reputation: 656

First you need to reshape the data:

library(tidyverse)
df <- df %>%
gather(variable, value, - YEAR, -ID, -CAT)

First option:

df <- mutate(df, CAT = as.character(CAT))
ggplot(df, aes(value, fill = CAT)) + 
geom_histogram(binwidth = 10, position = position_dodge())

Second option:

df <- df %>%
    mutate(value.buckets = cut_interval(value, length = 10))

df.CAT.buckets <- df %>%
    group_by(CAT, value.buckets) %>%
    summarise(count = n())

ggplot(df.CAT.buckets, aes(value.buckets, count, fill = CAT)) +
    geom_bar(stat = "identity", position = position_dodge())

Upvotes: 1

Related Questions