Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do i get "position_dodge requires constant width" even though widths are constant in ggplot2

Tags:

plot

r

ggplot2

I'm getting a warning message I don't understand for simple bar charts in ggplot2

> df <- data.frame(X = 127:131, Y = rnorm(5))
> df
    X          Y
1 127  0.9391077
2 128 -0.9392529
3 129 -1.1296221
4 130  1.1454907
5 131  1.8564596
> ggplot(df) + geom_bar(aes(X,Y), stat ="identity", position = "dodge")
Warning message:
position_dodge requires constant width: output may be incorrect 

It only seems to happen for certain ranges of X values. I've googled for info on this, but it all seems to be talking about cases when the widths genuinely are different, or cases where stat is not "identity". In this case the X values are just integers, so it should be simple.

The chart produced looks ok, so I'm uneasy about just ignoring a warning I don't understand.

Any idea what is going on?

like image 585
Corvus Avatar asked Jan 23 '13 10:01

Corvus


1 Answers

Setting options(warn = 2, error = recover), and rerunning the code lets us find the problem.

Inside the collide function (number 16 in the call stack), there is this piece of code:

if (!zero_range(range(widths))) {
    warning(name, " requires constant width: output may be incorrect", 
        call. = FALSE)
}

Floating point rounding errors mean that widths takes slightly different values.

format(widths, digits = 22)
# [1] "0.9000000000000056843419" "0.8999999999999914734872" "0.8999999999999772626325"

The tolerance for checking that the numbers are the same is too strict: about 2.2e-14.

args(zero_range)
# function (x, tol = .Machine$double.eps * 100) 
# NULL
.Machine$double.eps * 100
# [1] 2.220446e-14

So the warning is erroneous; don't worry about it.

like image 72
Richie Cotton Avatar answered Oct 08 '22 20:10

Richie Cotton