HappyPy
HappyPy

Reputation: 10697

plot counts with intervals in x axis using ggplot2

c1 <- c("p2","p3","p1","p2","p1","p3","p4","p4","p4","p1","p1","p2","p2","p3","p4","p2","p1","p4","p3","p3")
c2 <- c(41,146,79,107,131,127,32,88,119,148,32,65,36,23,44,76,100,98,121,104)

df <- data.frame(c1=c1, c2=c2)

I'm trying to create a stacked bar plot in ggplot2 with intervals in the x axis and counts in the y axis

Conceptually something like this

ggplot(df, aes(x=c2.intervals, y=count.c2.occurrences, fill=c1)) + geom_bar()

in which c2.intervals could be 0-70, 71-100, 100-150

For example, for the interval 0-70, p1 appears once, p2 3 times, p3 once and p4 twice. These would be the counts for the first stacked column in the plot.

What is the best way to approach this problem?

Upvotes: 2

Views: 897

Answers (1)

Z.Lin
Z.Lin

Reputation: 29095

You can use cut() to define your intervals. Also, based on your description, I assume you want fill = c1 rather than fill = c2?

See if the following serves your purpose:

library(dplyr)
df %>%
  mutate(c2.intervals = cut(c2, breaks = c(0, 70, 100, 150))) %>%
  ggplot(aes(x = c2.intervals, fill = c1)) +
  geom_bar()

plot

Upvotes: 3

Related Questions