【问题标题】:ggplot2: positioning tick marks on a four quadrant graph along the center axes (ie. x=0, y=0) instead of the border of the plotting areaggplot2:沿着中心轴(即x = 0,y = 0)而不是绘图区域的边界在四象限图上定位刻度线
【发布时间】:2019-06-27 22:27:19
【问题描述】:

我正在尝试调整我的绘图上刻度线的位置,使它们沿着轴而不是绘图的周边(这是默认设置)。我尝试在ggplot2 中使用axis.ticks 参数,但这不起作用。以下是一些示例数据和生成我正在使用的图表所需的代码:

library(ggplot2)
dat <- data.frame(v1 = c(1, 3, -2, 2, 1, 4, -2, 2),
                  v2 = c(-1, 2, 1, -3, 4, 1, -1, 2))
p = ggplot()
p + geom_point(aes(dat$v1, dat$v2) ,shape = 21, size = 3) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw()

请就任何可用于将刻度线移动到轴上而不是图形区域外边缘的包、函数或参数提供建议。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

汇集@user20650 的评论链接到Moving x or y axis together with tick labels to the middle of a single ggplot (no facets),共享@baptiste@user73708 的功能。我删除了您的虚线,并将数据和 aes 移至 ggplot 调用。

library(ggplot2)
dat <- data.frame(v1 = c(1, 3, -2, 2, 1, 4, -2, 2),
                  v2 = c(-1, 2, 1, -3, 4, 1, -1, 2))

shift_axis_y <- function(p, y=0){
  g <- ggplotGrob(p)
  dummy <- data.frame(y=y)
  ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]]
  p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))), 
                        ymax=y, ymin=y) +
    geom_hline(aes(yintercept=y), data = dummy) +
    theme(axis.text.x = element_blank(), 
          axis.ticks.x=element_blank())
}

shift_axis_x <- function(p, x=0){
      g <- ggplotGrob(p)
      dummy <- data.frame(x=x)
      ax <- g[["grobs"]][g$layout$name == "axis-l"][[1]]
      p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(x=1, width = sum(ax$height))), 
                            xmax=x, xmin=x) +
        geom_vline(aes(xintercept=x), data = dummy) +
        theme(axis.text.y = element_blank(), 
              axis.ticks.y=element_blank())
    }

p <- ggplot(dat, aes(v1, v2)) + 
  geom_point(shape = 21, size = 3) + 
  theme_bw()

p<-shift_axis_y(p, y=0)
p<-shift_axis_x(p, x=0)
p

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2019-02-08
    • 2011-03-29
    • 1970-01-01
    • 2022-11-18
    • 2017-07-18
    • 2023-01-30
    相关资源
    最近更新 更多