3

I want to add minor axis ticks and/or lines on a figure generated with ggplot(). This is a seemingly simple task but has proven very challenging. I found this solution but it is relatively inelegant and does not suit my application. I will be re-making my plot many times with different data, thus changing the axis limits and breaking any manual specifications via geom_vline().

I read the documentation for scales::minor_breaks_width() and tried to use it for the minor_breaks argument to scale_x_continuous() but it throws an error about "looping over the breaks".

A reprex is below, can anyone offer a suggestion?

library(tidyverse)

p <- mpg %>% 
  ggplot(aes(displ, hwy))+
  geom_point()

# major breaks are easy to set
p +
  scale_x_continuous(
    breaks = scales::breaks_width(width = 0.5, offset = 0))

# adding a minor breaks specification throws an error 
p +
  scale_x_continuous(
    breaks = scales::breaks_width(width = 0.5, offset = 0),
    minor_breaks = scales::minor_breaks_width(width = 0.01, offset = 0) )
#> Error in loop_breaks(range, breaks, f): argument "breaks" is missing, with no default

Created on 2020-11-19 by the reprex package (v0.3.0)

Evan M
  • 340
  • 2
  • 7
  • Apparently this is not very simple to do, but this guy has done it: https://stackoverflow.com/questions/34533472/insert-blanks-into-a-vector-for-e-g-minor-tick-labels-in-r – LuizZ Nov 20 '20 at 01:19

1 Answers1

0

Alternatively, you might want to try a simpler method. I used the width of 0.1 because it is difficult to see with 0.01.

library(tidyverse)
p <- mpg %>% 
  ggplot(aes(displ, hwy))+
  geom_point()

brks = seq(1.5, 7, 0.1)
lbs <- ifelse(brks%%0.5 == 0, format(brks, digits = 1, nsmall = 1), "")
p +
  scale_x_continuous(
    breaks = brks, labels = lbs) 

enter image description here

Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27