Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - Right align rotated axis title in ggplot2

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

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...