【问题标题】:Setting only certain tick marks in Ggplot2在 Ggplot2 中仅设置某些刻度线
【发布时间】:2021-03-25 10:19:58
【问题描述】:

我想重新创建以下绘图,该绘图仅在行首和行尾的 y 和 x 轴上显示刻度线。 Picture of Plot。 到目前为止,我有以下代码:

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

结果是这样的:Picture of result。它非常接近,但蜱虫仍然不见了...... 我可以删除所有轴刻度或不删除。但是如果不删除沿轴的 x 和 y 值,我无法设法仅设置某些轴刻度。

非常感谢任何帮助!

【问题讨论】:

    标签: r ggplot2 axis


    【解决方案1】:

    您可以使用scales 库中的pretty_breaks 函数:

    ggplot(dat, aes(x,y)) + geom_point() +
    scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
    scale_y_continuous(breaks = scales::pretty_breaks(n = 10))
    

    n 定义滴答数

    查看https://stackoverflow.com/a/31408489/15235792

    【讨论】:

      【解决方案2】:

      如果您将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 package (v1.0.0) 于 2021-03-25 创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多