J Lal
J Lal

Reputation: 49

ggplot2 - geom_histogram's binwidth with scale_x_log10

I'm trying to build an histogram with ggplot. I don't quite grasp how binwidth works.

 library(ggplot2)
 set.seed(10)
 testData = data.frame(x=rlnorm(100, log(1), log(2.5)))
 ggplot(data=testData, aes(x=testData$x)) +
 geom_histogram(binwidth=1)+scale_x_log10()

How do I get 1 bar per order of magnitude ? (ie. 1 bar between 10^-1 and 10^0, 1 bar between 10^0 and 10^1, ...)

Upvotes: 1

Views: 448

Answers (1)

GL_Li
GL_Li

Reputation: 1798

One way to do it is using cut() function to group the data and then count by the group

library(ggplot2)
set.seed(10)
x=rlnorm(100, log(1), log(2.5))
testData = data.frame(x = x, grp = cut(x, c(0.1, 1, 10)))
ggplot(data=testData, aes(grp)) +
    stat_count()

Upvotes: 1

Related Questions