0
votes

How do I set the axis range to be exactly as specified?

For the following example, I want the x-axis to cross at 0% (not -0.5% as pictured) and I want the top value to be 12% (not 12.5%)

I have tried both:

scale_x_continuous(limits = c(0, 0.12))

and

coord_cartesian(ylim = c(0, 0.12)) 

as per:

How to set limits for axes in ggplot2 R plots?

Can I limit ggplot axis range EXACTLY?

Sample code:

myData = data.frame(x = c(0, 1, 2, 3, 4, 5),
                  y = c(0.05,0.06, 0.07, 0.08, 0.09, 0.09))


ggplot() +
  geom_step(data=myData, aes(x=x, y=y), color='orange', size=1) +
  xlab('') +
  ylab('') +
  scale_y_continuous(labels = scales::percent, limits=c(0,0.12))


ggplot() +
  geom_step(data=myData, aes(x=x, y=y), color='blue', size=1) +
  xlab('') +
  ylab('') +
  scale_y_continuous(labels = scales::percent) + 
  coord_cartesian(ylim = c(0,0.12))

Result:

enter image description here

1

1 Answers

3
votes

Are you looking for expand?

coord_cartesian(ylim = c(0,0.12), expand=0)

or better (see comments)

scale_y_continuous(labels = scales::percent,
 expand = expand_scale(),
 limits = c(0,0.12))

enter image description here