tidyverse / tidyverse/ggplot2

Automatic limit setting in scale_*_binned leads to values being silently coerced to NA

Open
#6,806 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

scales :snake:
Dominant language
R
Stars
7k
Forks
2.1k
Avg merge
59m
Merged PRs (30d)
2

Description

When making a plot with scale_color_binned in 4.0.2 I discovered that when breaks are set manually, values may be displayed as NA even if they are within the bins specified. In the reprex below I make a scatter plot of hp vs mpg in the built-in mtcars dataset, with points colored by displacement. When we just set scale_color_binned with no options, everything looks fine:

Image

If we set manual breaks of (0, 100, 150, 200, 500), the rightmost point (which has displacement of 71.1) is now shown as gray (i.e. NA), despite being within the scale breaks:

Image

If we explicitly set the scale limits to (0, 500) the problem is solved:

Image

Reprex:

library(ggplot2)

data(mtcars)

min(mtcars$disp)
#> [1] 71.1

# this makes a scatter plot of hp vs mpg, with points colored by
# displacement; this works
ggplot(mtcars, aes(x=mpg, y=hp, color=disp)) +
    geom_point() +
    scale_color_binned()

# If we set breaks manually, the rightmost point is colored gray for
# NA even though it is within the breaks.
ggplot(mtcars, aes(x=mpg, y=hp, color=disp)) +
    geom_point() +
    scale_color_binned(breaks = c(0, 100, 150, 200, 500))

# explicitly setting limits solves the problem
ggplot(mtcars, aes(x=mpg, y=hp, color=disp)) +
    geom_point() +
    scale_color_binned(breaks = c(0, 100, 150, 200, 500),
        limits=c(0, 500))

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied mtcars reprex with scale_color_binned() and with manual breaks, then compare it with the explicit limits case. Trace the automatic limit-setting path for scale_color_binned and add a regression test for the 71.1 displacement value; done means values inside the supplied breaks are not coerced to NA.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
data-visualization
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.