ip2018
ip2018

Reputation: 715

Group observations in geom_histogram axis

A simple vector:

freq = c(1,2,2,3,3,3,4,4,4,4,5,5,5,5)

And a simple histogram:

ggplot(data=as.data.frame(freq), aes(x=freq)) + geom_histogram()

How do I count all observations with value, for example, >= 4 and show as one bar? Thanks.

Upvotes: 0

Views: 192

Answers (2)

tjebo
tjebo

Reputation: 23747

As per my comment. Just checked it, it works, but you have to specify the 'stat' parameter in geom_histogram:

require(ggplot2)
freq = c(1,2,2,3,3,3,4,4,4,4,5,5,5,5)
ggplot(data=as.data.frame(freq), aes(x = freq >=4)) + geom_histogram(stat = 'count')

If you want to group by value, you can create 'cuts' as seen here

You can also create the cuts directly in ggplot:

ggplot(data=as.data.frame(freq), aes(x = cut(freq, c(1,2,3), include.lowest = TRUE))) + 
#you need to make sure that the cuts actually represent the intervals you want!! 
  geom_histogram(stat = 'count')

enter image description here

Upvotes: 1

ip2018
ip2018

Reputation: 715

A possible way might be to replace all values >= 4 with 4 and then plot

freq[freq >=4] = 4

Upvotes: 0

Related Questions