mikebmassey
mikebmassey

Reputation: 8604

Create a bin for anything above X value in GGPlot2 Histogram

Using ggplot2, I want to create a histogram where anything above X is grouped into the final bin. For example, if most of my distribution was between 100 and 200, and I wanted to bin by 10, I would want anything above 200 to be binned in "200+".

# create some fake data    
id <- sample(1:100000, 10000, rep=T)
visits <- sample(1:1200,10000, rep=T)

#merge to create a dataframe
df <- data.frame(cbind(id,visits))

#plot the data
hist <- ggplot(df, aes(x=visits)) + geom_histogram(binwidth=50)

How can I limit the X axis, while still representing the data I want limit?

Upvotes: 13

Views: 8691

Answers (2)

mindless.panda
mindless.panda

Reputation: 4092

Perhaps you're looking for the breaks argument for geom_histogram:

# create some fake data    
id <- sample(1:100000, 10000, rep=T)
visits <- sample(1:1200,10000, rep=T)

#merge to create a dataframe
df <- data.frame(cbind(id,visits))

#plot the data
require(ggplot2)
ggplot(df, aes(x=visits)) +
  geom_histogram(breaks=c(seq(0, 200, by=10), max(visits)), position = "identity") +
  coord_cartesian(xlim=c(0,210))

This would look like this (with the caveats that the fake data looks pretty bad here and the axis need to be adjusted as well to match the breaks):

manual breaks on histogram

Edit:

Maybe someone else can weigh in here:

# create breaks and labels
brks <- c(seq(0, 200, by=10), max(visits))
lbls <- c(as.character(seq(0, 190, by=10)), "200+", "")
# true
length(brks)==length(lbls)

# hmmm
ggplot(df, aes(x=visits)) +
  geom_histogram(breaks=brks, position = "identity") +
  coord_cartesian(xlim=c(0,220)) +
  scale_x_continuous(labels=lbls)

The plot errors with:

Error in scale_labels.continuous(scale) : 
  Breaks and labels are different lengths

Which looks like this but that was fixed 8 months ago.

Upvotes: 6

Jojo
Jojo

Reputation: 5211

If you want to fudge it a little to get around the issues of bin labelling then just subset your data and create the binned values in a new sacrificial data-frame:

id <- sample(1:100000, 10000, rep=T)
visits <- sample(1:1200,10000, rep=T)

#merge to create a dataframe
df <- data.frame(cbind(id,visits))
#create sacrificical data frame
dfsac <- df
dfsac$visits[dfsac$visits > 200 ] <- 200

Then use the breaks command in scale_x_continuous to define your bin labels easily:

ggplot(data=dfsac, aes(dfsac$visits)) + 
  geom_histogram(breaks=c(seq(0, 200, by=10)), 
                 col="black", 
                 fill="red") +
  labs(x="Visits", y="Count")+
  scale_x_continuous(limits=c(0, 200), breaks=c(seq(0, 200, by=10)), labels=c(seq(0,190, by=10), "200+"))

enter image description here

Upvotes: 8

Related Questions