将y轴标题放在图的左上角 [英] Put y axis title in top left corner of graph

查看:248
本文介绍了将y轴标题放在图的左上角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用R中的ggplot2绘制一幅情节,我想让y轴的标题出现在情节的左上角。考虑以下代码的默认行为:

  require(ggplot2)

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

ggplot(data = xy)+
geom_point(aes(x = x,y = y))+
ylab(非常长的标签)

这产生了下面的图:





我想移动并旋转文本非常长的标签。我可以使用 theme()函数来做到这一点:

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

p>



您可以看到我要去的位置,但边距不正确 - 左边距太大,因为该空间是为旋转的标签保留的,而顶部边距对于文本来说太小。



如何告诉ggplot我希望在那个位置没有旋转的情况下使用y轴标题,并让它为它保留适当的空间?

解决方案

把它放在主标题中:

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

如果你喜欢,使用负值 hjust 值,尽管如果你太过分了,标签会被裁剪掉。在这种情况下,您可以尝试使用 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))

所以很显然,这很难为图形添加实际标题。您可以使用类似以下方式手动注释:

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

反之亦然,使用 grid.text code>为y标签。


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?

解决方案

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.

这篇关于将y轴标题放在图的左上角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆