在ggplot2中将旋转轴标题右对齐

时间:2018-10-27 23:35:28

标签: r ggplot2

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

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))

enter image description here

1 个答案:

答案 0 :(得分:5)

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

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 package(v0.2.1)于2018-10-27创建