在ggplot2中将旋转的轴标题右对齐 [英] Right align rotated axis title in ggplot2

查看:356
本文介绍了在ggplot2中将旋转的轴标题右对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Y轴标题(种类")与轴标签(三个种类名称)右对齐,以使轴标题靠近灰色面板? hjust似乎不影响位置.

How do I right-align the Y-axis title ("Species") with the axis labels (the three species names), such that the axis title is close to the gray panel? hjust does not seem to affect the position.

library(ggplot2)

ggplot(iris,
       aes(x = Species,
           y = Sepal.Width)) +
  geom_boxplot() +
  labs(x = "Species",
      y = "Sepal Width") +
  coord_flip() +
  theme(axis.title.y = element_text(angle = 0, hjust = 0))

推荐答案

您可以在coord_flip()中将geom_textclip = "off"一起使用,这将允许在绘图面板之外绘制绘图元素.显然,您必须使用xy才能通过此手动方法获得所需的输出

You can use geom_text together with clip = "off" inside coord_flip() which will allow drawing plot element outside of the plot panel. Obviously you will have to play around with x and y to get the desired output with this manual method

library(ggplot2)

p <- ggplot(iris,
       aes(x = Species,
           y = Sepal.Width)) +
  geom_boxplot() +
  labs(x = NULL,
       y = "Sepal Width") +
  coord_flip(clip = "off") + # add clip = off here
  theme(axis.title.y = element_text(angle = 0, hjust = 0))

p +
  # add axis title here
  geom_text(
    x = 3.5,
    y = 1.85,
    inherit.aes = FALSE,
    label = "Species",
    check_overlap = TRUE,
    hjust = 1,
    fontface = 'bold',
    size = 5
  ) +
  theme(plot.margin = unit(c(1, 1, 1, 2), "lines"))

reprex软件包(v0.2.1)

Created on 2018-10-27 by the reprex package (v0.2.1)

这篇关于在ggplot2中将旋转的轴标题右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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