【问题标题】:Increase the margin of every second x-axis tick ggplot2增加每隔一个 x 轴刻度 ggplot2 的边距
【发布时间】:2020-02-16 22:44:59
【问题描述】:

我正在寻找一种方法,让 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 个刻度,所以我无法手动设置)。

有什么想法吗?

编辑:

输出应该是:

编辑2:

一个更复杂的例子是:

#MWE
ggplot(diamonds, aes(cut, price, fill = clarity, group = clarity))+
geom_col(position = 'dodge')+
theme(
    axis.ticks.length.x = unit(15, "pt")
)

【问题讨论】:

  • 您好,您可以使用theme() 更改您的绘图布局。如果你想改变轴,这由scalefunctions 完成。对于您的情况scale_x_continuous(breaks=c(0,50,100))helps 与轴刻度。您可能应该添加一张图片来说明您想要增加的边距。

标签: r ggplot2 margin


【解决方案1】:

编辑 -- 在底部添加分类方法。

这是一个技巧。希望有更好的办法!

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")

这是用于分类 x 的类似方法。

cats <- sort(as.character(unique(diamonds$cut)))
ticks <- data.frame(x = cats)
ticks$y = ifelse(seq_along(cats) %% 2, -500, -2000)

ggplot(diamonds, aes(cut, price, fill = clarity, group = clarity))+
  geom_col(position = 'dodge') +
  annotate("rect", fill = "white",
           xmin = 0.4, xmax = length(cats) + 0.6,
           ymin = 0, ymax = -3000) +
  geom_segment(data = ticks, inherit.aes = F,
               aes(x = x, xend = x,
                   y = 0, yend = y))  +
  geom_text(data = ticks, inherit.aes = F,
            aes(x = x, y = y, label = x), vjust = 1.5) +
  scale_x_discrete(labels = NULL, name = "cut") +
  scale_y_continuous(expand = expand_scale(mult = c(0, 0.05))) +
  theme(axis.ticks.x = element_blank()) +
  coord_cartesian(clip = "off")

【讨论】:

  • 酷。我会接受这一点,因为它确实解决了这个问题。几个问题:(1)您会修改ticks 中的y 以增加间距吗? (2) 如果x 是分类的,(如果需要,我可以上传一个MWE)你会将ticks 中的x 更改为类别的顺序吗?我是否正确理解了您的解决方案?
  • 请看我的第二个例子,我没有设法让你的破解工作。谢谢!
  • 再次感谢您。出于某种原因(根据我的数据),y 轴随标签下降。你知道这个错误来自哪里吗?
  • 不确定。我添加了expand_scale(mult = c(0, 0.05))) 部分以指定y 轴不应低于从0 开始的数据。
  • 哦,好的,我的代码中也有这个。那时我会仔细检查。我现在刚刚完全移除了轴。
猜你喜欢
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 2018-05-27
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多