ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

scale_x_discrete(drop=FALSE) with 0-row datasets

Open pradosj opened this issue 10 months ago • 1 comments

Using ggplot2 3.5.2, I found a problem with scale_x_discrete(drop=FALSE) when input dataset is empty. Here is an example to reproduce the failure:

1 - Define an empty dataset with 2 factors

D <- tibble(
  a=factor(character(0),c("a1","a2")),
  b=factor(character(0),c("b1","b2","b3"))
)

2 - This is working:

ggplot(D,aes(x=a,y=b)) + 
  geom_tile()

3 - But adding scale_x_discrete(drop=FALSE) this is failing:

ggplot(D,aes(x=a,y=b)) + 
  geom_tile() + 
  scale_x_discrete(drop=FALSE)

Here is the error message and traceback of the failure:

Warning in rep(yes, length.out = len) :
  'x' is NULL so the result will be NULL

Error in ans[ypos] <- rep(yes, length.out = len)[ypos] : 
  replacement has length zero

17. ifelse(is.na(coord_limits), limits, coord_limits)
16. expand_limits_continuous_trans(range_continuous, expand, coord_limits,
trans)
15. expand_limits_discrete_trans(limits, expand, coord_limits, range_continuous = range_continuous)
14. expand_limits_discrete(limits, expand, coord_limits, range_continuous = scale$range_c$range)
13. expand_limits_scale(scale, expansion, limits, coord_limits = coord_limits)
12. view_scales_from_scale(scale_x, self$limits$x, self$expand)
11. setup_panel_params(..., self = self)
10. self$coord$setup_panel_params(scale_x, scale_y, params = self$coord_params)
9. (function (scale_x, scale_y)
{
self$coord$setup_panel_params(scale_x, scale_y, params = self$coord_params)
})(dots[[1L]][[1L]], dots[[2L]][[1L]])
8. mapply(FUN = f, ..., SIMPLIFY = FALSE)
7. Map(setup_panel_params, scales_x, scales_y)
6. setup_panel_params(..., self = self)
5. layout$setup_panel_params()
4. ggplot_build.ggplot(x)
3. ggplot_build(x)
2. print.ggplot(x)
1. (function (x, ...)
UseMethod("print"))(x)

pradosj avatar Jun 11 '25 14:06 pradosj

Thanks for the report! I can't reproduce this problem with the development version, so I expect it might have been fixed somewhere along the way?

teunbrand avatar Jun 11 '25 14:06 teunbrand

I'm going to consider this fixed in the development version.

teunbrand avatar Jun 19 '25 09:06 teunbrand