ggplot:y和x轴的移位位置

时间:2019-04-05 08:30:36

标签: r ggplot2

我想将y轴和x轴的位置更改为零,即使我的值为负。我在一个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

2 个答案:

答案 0 :(得分: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 :(得分: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)