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

5
我该如何将Y轴标题(“Species”)与轴标签(三个物种名称)右对齐,使轴标题靠近灰色面板?似乎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个回答

5
你可以在 coord_flip() 中使用 clip = "off"geom_text 结合使用,这将允许绘制图形元素超出图形面板。显然,您需要调整 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日。


我无法使用ggplot2版本3.0.0重现此图 - “Species”标签丢失了。 - Scransom
1
是的,更新后可以使用。最近的“小”更新差异意外地大... - Scransom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接