R语言 ggplot对齐主轴.刻度长度与次轴.刻度长度

fzsnzjdm  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(198)

让我们假设x轴从0到100。我想得到以下规格:

  1. 20秒时的刻度线和标签,即0、20、40、60、80、100,
    1.在10秒处,即在10、30、50、70、90、
  2. 5s时,无标签的刻度线长度为50%,即5、15、25等。
    我想到的一个想法是使用geom_segment()来放置额外的刻度线(2和3)。但是,这需要指定yyend,而刻度线需要指定单位长度,例如,“cm”。有没有一个简单的解决方案来相对于主刻度线的长度放置额外的刻度线,或者至少在同一个单位
    从示例性图表中可以看出,刻度线的放置如预期的那样工作,但是刻度线的长度没有对齐。


的数据
代码:

library(ggplot2)
set.seed(123)
df <- data.frame(x = rnorm(1000, mean = 50, sd = 10),
                 y = rnorm(1000, mean = 50, sd = 7))

# obtain difference between breaks with and without labels
xminor <- setdiff(seq(0, 100, 5), seq(0, 100, 20))
segment_data = data.frame(
  x = xminor,
  xend = xminor, 
  y = 0,
  yend = ifelse(xminor%%10 == 0, 3, 2)
)

ggplot() +
  geom_point(data = df, aes(x = x, y = y)) +
  geom_segment(data = segment_data,
               aes(x = x, xend = xend, y = y, yend = yend)) +
  scale_x_continuous(breaks = seq(0, 100, 20),
                     labels = seq(0, 100, 20), 
                     limits = c(0, 100),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,100),
                     expand = c(0, 0)) +
  theme(
    panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5),
    axis.ticks.x = element_line(linewidth = 0.5, color = "black"),
    axis.ticks.length.x = unit(-0.5, "cm"))

字符串

dzhpxtsq

dzhpxtsq1#

您可以通过完全删除轴刻度并在精确位置使用polylineGrob注解以及所需的精确长度来完成此操作。这也意味着您不需要segmentdata数据框。

ggplot() +
  geom_point(data = df, aes(x = x, y = y)) +
  annotation_custom(grid::polylineGrob(
                      x = rep(0:20/20, each = 2), 
                      y = unit(rep(c(0, 0.5, 0, 0.25), length = 42), 'cm'),
                      id = rep(0:20, each = 2))) +
  scale_x_continuous(breaks = seq(0, 100, 20),
                     limits = c(0, 100),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,100),
                     expand = c(0, 0)) +
  theme(
    panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5),
    axis.ticks.x = element_blank(),
    plot.margin = margin(10, 20, 10, 20))

字符串


的数据
请注意,如果设置了coord_cartesian(clip = 'off'),这也适用于绘图面板外部的刻度

ggplot() +
  geom_point(data = df, aes(x = x, y = y)) +
  annotation_custom(grid::polylineGrob(rep(0:20/20, each = 2), 
                      unit(rep(c(0, -0.5, 0, -0.25), length = 42), 'cm'),
                                    id = rep(0:20, each = 2))) +
  scale_x_continuous(breaks = seq(0, 100, 20),
                     limits = c(0, 100),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,100),
                     expand = c(0, 0)) +
  theme(
    panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5),
    axis.ticks.x = element_line(color = NA),
    axis.ticks.length.x = unit(0.5, 'cm'),
    plot.margin = margin(10, 20, 10, 20)) +
  coord_cartesian(clip = 'off')

相关问题