Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Put y axis title in top left corner of graph

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:

Original 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:

modified graph

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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...