将x或y轴与刻度标签一起移动到单个ggplot的中间(无小平面) [英] Moving x or y axis together with tick labels to the middle of a single ggplot (no facets)

查看:184
本文介绍了将x或y轴与刻度标签一起移动到单个ggplot的中间(无小平面)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Excel中创建了以下图:



但是后来我认为我会用ggplot使它更漂亮。我得到了这一点:





很好奇,数据基于我的


I made the following plot in Excel:

But then I thought I would make it prettier by using ggplot. I got this far:

If you're curious, the data is based on my answer here, although it doesn't really matter. The plot is a standard ggplot2 construct with some prettification, and the thick line for the x-axis through the middle is achieved with p + geom_hline(aes(yintercept=0)) (p is the ggplot object).

I feel that the axis configuration in the Excel plot is better. It emphasizes the 0 line (important when the data is money) and finding intercepts is much easier since you don't have to follow lines from all the way at the bottom. This is also how people draw axes when plotting on paper or boards.

Can the axis be moved like this in ggplot as well? I want not just the line, but the tick labels as well moved. If yes, how? If no, is the reason technical or by design? If by design, why was the decision made?

解决方案

try this,

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 <- qplot(1:10, 1:10) + theme_bw() 
shift_axis(p, 5)

这篇关于将x或y轴与刻度标签一起移动到单个ggplot的中间(无小平面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆