首页 > 解决方案 > 在 Ggplot2 中仅设置某些刻度线

问题描述

我想重新创建下面的图,它只在行首和行尾的 y 和 x 轴上显示刻度线。 情节的图片。到目前为止,我有以下代码:

elevation_plot <- StradeBianche%>%
  ggplot(aes(x = `Accumulated Distance in Km`))+
  geom_area(aes(y = elevation), fill = "grey")+
  coord_cartesian(ylim = c(100,500))+
  scale_y_continuous(expand = c(0,0), limits = c(0, 500),  labels = label_number(suffix = " m"))+
  scale_x_continuous(expand = c(0,0), breaks = seq(0, 180, 20), labels = label_number(suffix = ".0 km"))+
  theme(panel.grid.minor = element_blank())+
  theme(panel.grid.major = element_blank())+
  theme(panel.background = element_rect(fill = "white"))+
  theme(panel.border = element_blank())+
  theme(axis.title = element_blank())+
  theme(axis.ticks = element_blank())

结果是这样的: 结果图片。它非常接近,但仍然缺少刻度......我可以删除所有轴刻度或不删除。但是如果不删除沿轴的 x 和 y 值,我无法设法仅设置某些轴刻度。

任何帮助是极大的赞赏!

标签: rggplot2axis

解决方案


如果将geom_segment()s 放置在正确的坐标处并关闭数据的裁剪,则可以模仿刻度行为。缺点是您不能以绝对单位将分段端点相对于第一个端点放置,因此您必须摆弄偏移量和文本边距。下面的例子:

library(ggplot2)

xlim <- c(1, 5)
ylim <- c(4, 8)
offset <- 0.05

seg <- data.frame(
  x    = xlim[c(1,2,1,1)],
  xend = xlim[c(1,2,1,1)] - c(0, 0, offset, offset),
  y    = ylim[c(1,1,2,1)],
  yend = ylim[c(1,1,2,1)] - c(offset, offset, 0, 0)
)

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point(aes(colour = Species)) +
  geom_segment(data = seg, aes(x = x, y = y, xend = xend, yend = yend)) +
  coord_cartesian(clip = "off",
                  xlim = xlim,
                  ylim = ylim, 
                  expand = FALSE) +
  theme(axis.ticks = element_blank(),
        axis.line = element_line(),
        axis.text.x = element_text(margin = margin(t = 8)),
        axis.text.y = element_text(margin = margin(r = 8)))

reprex 包于 2021-03-25 创建(v1.0.0)


推荐阅读