增加每第二个x轴刻度ggplot2的边距

问题描述 投票:0回答:1

我正在寻找一种方法,可以使x-axis每秒向下跳动,并使tick行向下移动。我可以使用以下方法更改所有刻度线的常规边距和刻度线长度:

#MWE
library(ggplot2)
ggplot(cars, aes(dist, speed))+
   geom_point()+
   theme(
       axis.ticks.length.x = unit(15, "pt")
   )

但是,我希望x轴刻度0、50和100(即第二个刻度)没有增加的顶部边距。最好选择一个广义的答案,因为我的x轴是分类的而不是数字的(并且包含430个刻度,所以我无法手动设置任何内容)。

有什么想法吗?

编辑:

输出应为:enter image description here

r ggplot2 margin
1个回答
0
投票

这里是骇客。希望有更好的方法!

ticks <- data.frame(
  x = 25*0:5,
  y = rep(c(-0.2, -2), 3)
)

ggplot(cars, aes(dist, speed))+
  geom_point()+
  geom_rect(fill = "white", xmin = -Inf, xmax = Inf,
            ymin = 0, ymax = -5) +
  geom_segment(data = ticks,
               aes(x = x, xend = x,
                   y = 0, yend = y)) +
  geom_text(data = ticks,
            aes(x = x, y = y, label = x), vjust = 1.5) +
  theme(axis.ticks.x = element_blank()) +
  scale_x_continuous(breaks = 25*0:5, labels = NULL, name = "") +
  coord_cartesian(clip = "off")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.