在basic plot中实现

1
minor.tick(nx=3, ny=3, tick.ratio=0.5)

img

ggplot实现

在ggplot中反而没有发现很便捷的解决方案,虽然在scale_x_continuous()函数中有minor_breaks参数,但并不是直接对应刻度线的设置。

目前找到折中的解决方案是在指定breaks的同时指定lables,而lables在指定次级刻度时留空。其实,如此并没有设定次级刻度,只是在部分刻度上留空,视觉上看起来像是次级刻度罢了。具体方案如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#首先设定一个函数
#replace every x element with an empty charactor
every_nth <- function(x, nth, empty = TRUE, inverse = FALSE) 
  {
  if (!inverse) {
    if(empty) {
      x[1:nth == 1] <- ""
      x
      } else {
        x[1:nth != 1]
        }
    } else {
      if(empty) {
        x[1:nth != 1] <- ""
        x
        } else {
          x[1:nth == 1]
        }
    }
}

# example
library(ggplot2)
df <- data.frame(x = rnorm(1000), y = rnorm(1000))

## ggplot2 default axis labelling
p <- ggplot(df, aes(x, y)) + geom_point() + theme_bw()
## Add minor ticks to axes
custom_breaks <- seq(-3, 3, 0.25)
p + 
  scale_x_continuous(breaks = custom_breaks,
                     labels = every_nth(custom_breaks, 4, inverse = TRUE)) + 
  scale_y_continuous(breaks = custom_breaks,
                     labels = every_nth(custom_breaks, 2, inverse = TRUE)) 

custom labelling

参考来源

https://www.cnblogs.com/hdu-2010/p/3833088.html

https://stackoverflow.com/questions/34533472/insert-blanks-into-a-vector-for-e-g-minor-tick-labels-in-r/34533473#34533473

https://www.cnblogs.com/hdu-2010/p/3833088.html