Retrieving the range/limit of discrete scale in ggplot2

Viewed 435

I want to retrieve the range/limit of the x-axis when I plot a discrete variable on it. Specifically, I'm looking at the following code

library(tidyverse)

p <- mtcars %>%
  mutate(am = ifelse(am == 0, "Auto", "Manual")) %>%
  ggplot() + 
  geom_point(aes(factor(am), mpg)) 

p

variable am on the x-axis

There's a lot of space around the "Auto" and "Manual" tick marks. I know that if I inspect the p object, the x-axis tick marks are at x = 1 and 2 on a continuous scale, but I would like to know how far the x-axis extends, or what algorithm generates the limits.

> layer_scales(p)$x$range
<ggproto object: Class RangeDiscrete, Range, gg>
    range: Auto Manual
    reset: function
    train: function
    super:  <ggproto object: Class RangeDiscrete, Range, gg>

> layer_scales(p)$x$range_c
<ggproto object: Class RangeContinuous, Range, gg>
    range: 1 2
    reset: function
    train: function
    super:  <ggproto object: Class RangeContinuous, Range, gg>
0 Answers
Related