Put y axis title in top left corner of graph

2019-05-07 18:43发布

问题:

I'm drawing a plot with ggplot2 in R and I'd like the title for the y axis to appear in the top left corner of the plot. Consider the following code for the default behaviour:

require(ggplot2)

xy = data.frame(x=1:10, y=10:1)

ggplot(data = xy) +
  geom_point(aes(x = x, y = y)) +
  ylab("very long label")

This produces the following graph:

I would like to move and rotate the text "very long label". I can do this somewhat using the theme() function:

ggplot(data = xy) +
  geom_point(aes(x = x, y = y)) +
  ylab("very long label") +
  theme(axis.title.y = element_text(angle = 0, vjust = 1.1, hjust = 10))

Which gives me this:

You can see where I'm going with this, but the margins are incorrect -- the left margin is too large because the space is reserved for a rotated label and the top margin is too small for the text.

How can I tell ggplot that I want the y axis title at that position without rotation and have it reserve the appropriate space for it?

回答1:

Put it in the main plot title:

ggplot(data = xy) +
  geom_point(aes(x = x, y = y)) +
  ggtitle("very long label") +
  theme(plot.title = element_text(hjust = 0))

You can shove it slightly more to the left if you like using negative hjust values, although if you go too far the label will be clipped. In that case you might try playing with the plot.margin:

ggplot(data = xy) +
  geom_point(aes(x = x, y = y)) +
  ggtitle("very long label") +
  theme(plot.title = element_text(hjust = -0.3),
        plot.margin = rep(grid::unit(0.75,"in"),4))

So obviously this makes it difficult to add an actual title to the graph. You can always annotate manually using something like:

grid.text("Actual Title",y = unit(0.95,"npc"))

Or, vice-versa, use grid.text for the y label.



标签: r ggplot2