-1

Good afternoon. Recently I've faced a problem with building histograms in R. I type: Hist_SP500hist<-hist(SP500logreturns,col="lightblue",breaks = 140, border="white",main="", xlab="Time",xlim=c(-0.001,0.001))

Here I specify, that the number of breaks=140. But when I type Hist_SP500hist$breaks I get 179 breaks. How could it happen?

Rui Barradas
  • 57,195
  • 8
  • 29
  • 57
Maxim
  • 89
  • 2
  • 9
  • 1
    In order for us to help you, please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). For example, to produce a minimal data set, you can use `head()`, `subset()`, or the indices. Then use `dput()` to give us something that can be put in R immediately. Also, please make sure you know what to do [when someone answers your question](https://stackoverflow.com/help/someone-answers). More info can be found at Stack Overflow's [help center](https://stackoverflow.com/help). Thank you! – iamericfletcher Sep 05 '20 at 20:54
  • 1
    From `help('hist')`: *"the number is a suggestion only"*. Create a breakpoints sequence `brk – Rui Barradas Sep 05 '20 at 21:07

1 Answers1

3

You can manually adjust the breaks inside hist if you save it to an object. Here is and example using the faithful dataset

Note: I don't have enough reputation to show the graphs the code produces

waiting.hist <- hist(faithful$waiting)

edit: Since the breaks do not change the counts, you will have to update the counts too. Otherwise the counts will be recycled

waiting.hist$breaks <- seq(40, 100, 2.5)
waiting.hist$counts <- table(cut(faithful$waiting, seq(40, 100, 2.5)))

plot(waiting.hist)

Or you could use ggplot2 and specify the breaks using bins or binwidth

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.3
#> Warning: package 'ggplot2' was built under R version 3.6.3
#> Warning: package 'tibble' was built under R version 3.6.3
#> Warning: package 'tidyr' was built under R version 3.6.3
#> Warning: package 'purrr' was built under R version 3.6.3
#> Warning: package 'dplyr' was built under R version 3.6.3
#> Warning: package 'forcats' was built under R version 3.6.3
faithful %>% 
  ggplot(aes(x = waiting)) + 
  geom_histogram(bins = 30)

faithful %>% 
  ggplot(aes(x = waiting)) + 
  geom_histogram(binwidth = 2.5)

Created on 2020-09-05 by the reprex package (v0.3.0)

brinyprawn
  • 88
  • 5