drew
drew

Reputation: 285

How to dynamically set histogram binwidth

I am a total R noob learning ggplot. I don't understand why the first snippet works while the second doesn't. I wanted to find a good binwidth without guessing, so I tried an experiment that didn't work.

library(ggplot2)
attach(diamonds)
d <- diamonds
x <- ggplot(d, aes(x = price))
x <- x + geom_histogram(binwidth = 50)
x
# worked fine, but using the sequence and substituting i didn't
i <- seq(1, 101, by = 10)  #tried to avoid the first arg as zero, but didn't work
x <- ggplot(d, aes(x = price))
x <- x + geom_histogram(binwidth = i) 
x

the second throws an error

Error in seq.default(round_any(range[1], size, floor), round_any(range[2],  : 
  'from' must be of length 1
Error in exists(name, envir = env, mode = mode) : 
  argument "env" is missing, with no default

I don't understand what it wants. Thanks a lot

Upvotes: 9

Views: 1338

Answers (2)

JasonAizkalns
JasonAizkalns

Reputation: 20463

You may also want to consider the package manipulate if you are using RStudio:

install.packages("manipulate")
library(manipulate)
library(ggplot2)

df <- diamonds

manipulate(
  ggplot(df, aes(x = price)) +
    geom_histogram(binwidth = mybinwidth),
  mybinwidth = slider(10, 100, step = 10, initial = 20)
)

Picture of Manipulate

Aside: Please note that you do not need to attach(diamonds) if you are using ggplot2. Moreover, many people will argue against using attach altogether - and you may want to break the habit now. For example, the following works just fine:

ggplot(diamonds, aes(x = price)) + geom_histogram()

Upvotes: 2

Metrics
Metrics

Reputation: 15458

Try this:

i<-seq(1,101, by=10)  
x1<- ggplot(d, aes(x=price))
x2<-lapply(i,function(i)
x1+geom_histogram(binwidth=i)

)
To access each plot:
x2[[1]] # for bw 1
x2[[2]] #bw 11 and so on

Upvotes: 1

Related Questions