datazang
datazang

Reputation: 1159

How to define bins in ggplot2?

I've been working with a data set that looks the below data set:

data <- tribble(
  ~id,   ~min,    ~max,
  "1",     5,      40,
  "2",     6,      50,
  "3",     7,      70,
  "4",     8,      90,
  "5",    23,     100,
  "6",    18,      40,
  "7",    34,      50,
  "8",    84,     150,
  "9",    15,      70,
  "10",  100,      90,
)

Now, I want to plot the histogram by defining the range of bins. I've already plotted the below histogram, and now want to set the range of the bins on the X-axis like this: 0-5, 10-20, 30-50, 50-100.

enter image description here

Here is my code. Any suggestion?

ggplot(data=data, aes(data$min)) + 
  geom_histogram(breaks = seq(0, 100, by = 10), 
                 col = "black", 
                 fill = "red", 
                 alpha = .2) + 
  labs(x = "Min", y = "Count") 

Upvotes: 1

Views: 352

Answers (1)

eastclintw00d
eastclintw00d

Reputation: 2364

Adjust breaks to your needs:

ggplot(data=data, aes(data$min)) + 
  geom_histogram(breaks = c(0, 5, 10, 20 , 30, 50, 100), 
                 col = "black", 
                 fill = "red", 
                 alpha = .2,
                 ) + 
  labs(x = "Min", y = "Count") 

Upvotes: 1

Related Questions