ggplot: 移动 y 和 x 轴的位置

3

我希望能够将y轴和x轴的位置设为0,即使数据中存在负数。我在Google小组中读到说当时使用ggplot不可能实现这种功能。那么这个功能是否已经被实现了呢?

例如,当我的数据如下:

library(ggplot2)

df1 <- data.frame(
  S = rep(c(10, 5, 3.3, 2.5, 1.66, 0.62), 2),
  v = c(c(0.202, 0.079, 0.0597, 0.0565, 0.0365, 0.0318), 
        c(0.25, 0.14, 0.07, 0.06, 0.04, 0.03)),
  inhibitor = rep(c("nein", "ja"), each = 6)
)

我希望根据我手动添加的hlinevline来改变轴的位置。
ggplot(df1, aes(y = v, x = S, shape = inhibitor)) + 
  geom_point() +
  xlim(c(-2, 10)) + 
  geom_smooth(aes(linetype = inhibitor), 
              method = "lm", se = FALSE, 
              fullrange = TRUE, color = "black") +
  geom_vline(xintercept = 0) +
  geom_hline(yintercept = 0)

enter image description here


你需要使用 + coord_cartesian(xlim = c(0, 10), ylim = c(0, 0.25)) 吗?这将放大你的绘图。请参考 https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf 的第二页,右下角。 - markus
不,我希望hlinevline成为坐标轴的线条(包括刻度线和其他所有内容)。 - j3ypi
2个回答

0
你是在说要移除坐标轴和坐标轴标签之间的空白吗?
ggplot2中scale函数中的“expand”参数设置了图表限制和轴之间的填充。
ggplot(df1, aes(y = v, x = S, shape = inhibitor)) + 
    geom_point() +
    xlim(c(-2, 10)) + 
    geom_smooth(aes(linetype = inhibitor), 
                method = "lm", se = FALSE, 
                fullrange = TRUE, color = "black") +
    geom_vline(xintercept = 0) +
    geom_hline(yintercept = 0) + 
    scale_x_continuous(expand=c(0,0)) +
    scale_y_continuous(expand=c(0,0))

enter image description here


1
不,我也需要负空间。我想要与我的示例中完全相同的框架,但是y轴位于“geom_vline()”的位置,而x轴位于“geom_hline()”的位置。 - j3ypi

0

#试试这段代码。我在搜索时找到的:

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

#p是你的ggplot代码,请运行它,然后运行:

shift_axis(p, 0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接