首页 > 解决方案 > 将轴标题与轴边缘完美对齐

问题描述

对于ggplot2绘图,hjustvjust是相对于整个绘图定义的对齐函数。因此,当它们应用于轴标签时,它们不是相对于轴线定义的。

但是,相对于轴线调整轴标题更为自然。

具体来说,我正在寻找一种左对齐x轴标题以及顶部对齐和旋转y轴标题的方法。

怎么能做到这一点?

对齐的轴标题

标签: rggplot2

解决方案


如问题中所述,hjust并且vjust是相对于整个图定义的对齐函数。

因此,hjust=0将不会实现相对于x轴线起点的完美左对齐。但是,它可以与expand_limits和结合使用scale_x_continuous

与轴标题类似scale_y_continuousy

在问题的附加图像中,情节从原点开始。所以首先,我们必须强制情节从原点开始:

... +
  expand_limits(x = 0, y = 0) +
  scale_x_continuous(expand = c(0, 0)) + 
  scale_y_continuous(expand = c(0, 0))

然后我们可以指定调整——这里还添加了y轴标题的旋转,这需要我们使用hjust而不是vjust

... +
theme(
  axis.title.x = element_text(hjust = 0),
  axis.title.x = element_text(angle = 90, hjust = 1)
)

完整的工作示例

首先,我们加载ggplot2并创建一个数据集:

library(ggplot2) 

df <- data.frame(
  x = c(0, 50, 100),
  y = c(20, 40, 80)
)

我们创建情节并添加一个geom_line().

graph <- 
  ggplot(data=df, mapping = aes(x=x, y=y)) +
  geom_line()

我们修复我们的轴。作为更好地控制轴的额外奖励,我还定义了轴范围 ( limits)。

graph <-
  graph +
  scale_x_continuous(expand = c(0,0), limits = c(min(df$x), max(df$x))) +
  scale_y_continuous(expand = c(0,0), limits = c(min(df$y), max(df$y)))

然后,我们格式化轴标题。为了更好的视觉表现,我还添加了一个边距,使标题稍微远离轴线。

graph <-
  graph +
  theme(
    axis.title.x = element_text(hjust = 0, margin = margin(t=6)),
    axis.title.y = element_text(angle = 90, hjust = 1, margin=margin(r=6))
  )

最后,我们添加轴标题:

graph <-
  graph +
  xlab("This is the x axis") + 
  ylab("This is the y axis")

结果:

在此处输入图像描述

但是,这会切断最后一个标签文本(100 中的最后一个 0 仅部分可见)。为了解决这个问题,我们必须增加绘图边距,这里以四周 1 厘米的边距为例:

graph <-
  graph +
  theme(plot.margin = margin(1, 1, 1, 1, "cm"))

最终结果:

在此处输入图像描述

完整代码

library(ggplot2)


df <- data.frame(
  x = c(0, 50, 100),
  y = c(20, 40, 80)
)

graph <-
  ggplot(data=df, mapping = aes(x=x, y=y)) +
  geom_line() +
  expand_limits(x = 0, y = 0) +
  scale_x_continuous(expand = c(0,0), limits = c(min(df$x), max(df$x))) +
  scale_y_continuous(expand = c(0,0), limits = c(min(df$y), max(df$y))) +
  theme(
    axis.title.x = element_text(hjust = 0, margin = margin(t=6)),
    axis.title.y = element_text(angle = 90, hjust = 1, margin=margin(r=6)),
    plot.margin = margin(1, 1, 1, 1, "cm")
  ) +
  xlab("This is the x axis") + 
  ylab("This is the y axis")
    
  

推荐阅读