Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set number of bins for histogram directly in ggplot

Tags:

I'd like to feed geom_histogram the number of bins for my histogram instead of controlling bins through binwidth. The documentation says I can do this by setting the bins argument. But when I run

ggplot(data = iris, aes(x = Sepal.Length)) + stat_bin(bins = 5) 

I get an output message with 30 bins, as if I didn't specify binwidth at all.

stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

I've tried feeding this argument to stat_bin and qplot with the same problem. Am I doing something wrong?

I'm using ggplot2 version 1.0.1.

like image 552
Empiromancer Avatar asked Jan 13 '16 18:01

Empiromancer


People also ask

How do I change the number of bins in a Ggplot histogram?

To change the number of bins in the histogram using the ggplot2 package library in the R Language, we use the bins argument of the geom_histogram() function. The bins argument of the geom_histogram() function to manually set the number of bars, cells, or bins the whole histogram will be divided into.

How do you increase the number of bins in a histogram?

N = morebins( h ) increases the number of bins in histogram h by 10% (rounded up to the nearest integer) and returns the new number of bins. For bivariate histograms, this increases the bin count in both the x and y directions.

What is the default method each uses to determine the number of bins?

Base R hist function uses the Sturges method to calculate the number of bins, which is a good default.

How do you find the number of bins in a histogram in R?

Calculate the number of bins by taking the square root of the number of data points and round up. Calculate the bin width by dividing the specification tolerance or range (USL-LSL or Max-Min value) by the # of bins.


1 Answers

Just pass bins=x directly

library(ggplot2) df <- data.frame(a = rnorm(10000))  ggplot(df, aes(x=a)) + geom_histogram() 

Produces this (with warning "stat_bin() using bins = 30. Pick better value with binwidth."):

enter image description here

And this:

ggplot(df, aes(x=a)) + geom_histogram(bins=10) 

Produces:

enter image description here

Using ggplot2 version 2.0.0

like image 168
arvi1000 Avatar answered Sep 29 '22 00:09

arvi1000