how to get a histogram with 10 bins from 0 to 1

78 views
Skip to first unread message

Alberto Lusiani

unread,
Jun 19, 2016, 5:55:52 PM6/19/16
to ggplot2, Alberto Lusiani
I want to plot a histogram with 10 bins evenly spaced from 0 to 1.

I can get that with:

require(ggplot2)
require(scales, quiet=TRUE)

df = data.frame(x = (0.5 + seq(0, 30))/20)

##
## produces what I want: 10 bins evenly spaced from 0 to 1 all with count=2
##
ggplot(df, aes(x=x))+
  geom_histogram(breaks=seq(0, 1, length.out=10+1)) +
  scale_x_continuous(breaks=pretty_breaks(10), limits=c(0,1)) +
  coord_cartesian(xlim = c(0, 1)) +
  theme_bw()

(I am aware that scale_x_continuous/limits and coord_cartesian/xlim are similar/overlapping statements)

Is there another simpler method to get what I am looking for?

I have tried as follows, but I don't obtain the bins as I would expect to:

##
## produces n bins, all count=2, from 0.05 to 0.95
##
ggplot(df, aes(x=x))+
  geom_histogram(binwidth=1/10) +
  scale_x_continuous(breaks=pretty_breaks(10), limits=c(0,1)) +
  coord_cartesian(xlim = c(0, 1)) +
  theme_bw()

##
## produces n bins, 2 with count=3, the other ones with count=2
## from 0.05 to 0.95
##
ggplot(df, aes(x=x))+
  geom_histogram(bins=10) +
  scale_x_continuous(breaks=pretty_breaks(10), limits=c(0,1)) +
  coord_cartesian(xlim = c(0, 1)) +
  theme_bw()

Here is my environment:

platform       x86_64-redhat-linux-gnu     
arch           x86_64                      
os             linux-gnu                   
system         x86_64, linux-gnu           
status                                     
major          3                           
minor          3.0                         
year           2016                        
month          05                          
day            03                          
svn rev        70573                       
language       R                           
version.string R version 3.3.0 (2016-05-03)
nickname       Supposedly Educational      

packageVersion("ggplot2")
[1] ‘2.1.0’

Best regards,
--
Alberto

Hadley Wickham

unread,
Jun 20, 2016, 12:01:57 PM6/20/16
to Alberto Lusiani, ggplot2
On Sun, Jun 19, 2016 at 4:53 PM, Alberto Lusiani <alus...@gmail.com> wrote:
> I want to plot a histogram with 10 bins evenly spaced from 0 to 1.
>
> I can get that with:
>
> require(ggplot2)
> require(scales, quiet=TRUE)
>
> df = data.frame(x = (0.5 + seq(0, 30))/20)

Your data goes from 0.025 to 1.525 ?

Hadley

--
http://hadley.nz

Alberto Lusiani

unread,
Jun 20, 2016, 2:59:59 PM6/20/16
to ggplot2, alus...@gmail.com
yes, but I am interested in plotting them only in the range [0-1]. I generate more data to check the effect of xlim/limits when ggplot2 automatically computes the bins.

Greetings,
--
Alberto
Reply all
Reply to author
Forward
0 new messages