移动 ggplot 的坐标轴标签

32

我使用ggplot2制作了一个事实图,但是x轴标题(底部)与刻度值稍微接触了一下(当我绘制到.pdf设备时会更加糟糕)。我该如何将坐标轴标题下移一点?

DF<-structure(list(race = structure(c(3L, 1L, 3L, 2L, 3L, 1L, 2L, 
2L, 2L, 3L, 2L, 1L, 3L, 3L, 3L, 3L, 2L, 1L, 2L, 3L), .Label = c("asian", 
"black", "white"), class = "factor"), gender = structure(c(1L, 
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 
2L, 2L, 2L), .Label = c("female", "male"), class = "factor"), 
    score = c(0.0360497844302483, 0.149771418578119, 0.703017688328021, 
    1.32540102136392, 0.627084455719946, -0.320051801571444, 
    0.852281028633536, -0.440056896755573, 0.621765489966213, 
    0.58981396944136, 1.95257757882381, 0.127301498272644, -0.0906338578670778, 
    -0.637727808028146, -0.449607617033673, 1.03162398117388, 
    0.334259623567608, 0.0912327543652576, -0.0789977852804991, 
    0.511696466039959), time1 = c(75.9849658266583, 38.7148843859919, 
    54.3512613852158, 37.3210772390582, 83.8061071736856, 14.3853324033061, 
    79.2285735003004, 31.1324602891428, 22.2294730114138, 26.427263191766, 
    40.5529893144888, 19.2463281412667, 8.45085646487301, 97.6770352620696, 
    61.1874163107771, 31.3727683430548, 99.4155144857594, 79.0996849438957, 
    21.2504885323517, 94.1079332400361)), .Names = c("race", 
"gender", "score", "time1"), class = "data.frame", row.names = c(NA, 
-20L))


require(ggplot2)
p <- ggplot(DF, aes(score, time1, group=gender))
p + geom_point(aes(shape=19)) + facet_grid(race~gender) + scale_x_continuous('BLAH BLAH') + 
scale_y_continuous('Some MOre Of theat Good Blahing') 

在我的数据中,BLAH BLAH与数字相接触。我需要它往下移动。怎么做?


嗯,你能详细说明一下它的外观或者发布一个示例图片吗?因为当我运行这个程序时,它看起来很好。可能是特定于平台/设备/图像大小的问题。 - joran
@joran 我不能发布这张图片或数据,因为我在使用别人的数据。但我尽力了,在这个数据集之外我无法复制出问题。 - Tyler Rinker
没问题...我看到你已经得到了指针来调整对齐方式。我只是很好奇,因为我无法复制它。 - joran
3个回答

43

您可以使用以下方法调整x轴标题的位置:

+ opts(axis.title.x = theme_text(vjust=-0.5))

尝试调整-0.5的“垂直对齐”参数,直到它适合您/您的显示设备。


104
请记住,现在已经不推荐使用opts和theme_text。您应该使用theme(axis.title.x = element_text(vjust=-0.5))。 - Eduardo
2
有没有相应的方法可以在保留文本排列的同时水平改变其位置?hjust似乎只能改变文本对齐方式,而我只想改变位置。 - kennyB
19
自从ggplot 2.0.0版本以来,vjust参数已被margins取代。可以为顶部(t)、右侧(r)、底部(b)和左侧(l)指定边距来垂直和水平定位文本。因此,要向下移动文本,您将使用 theme(axis.title.x = element_text(margin = margin(t = 20)) - JWilliman

12

这是一个简单的解决方法,基于提供在这里的回答。

只需在轴标题的开头添加一个换行符\nxlab("\n您的_x_标签")(或者在末尾如果您需要移动y标签)。

它提供的控制不如评论中Eduardo的建议theme(axis.title.x = element_text(vjust=-0.5))或使用margin,但它更加简单!


2

我想指出的是,这不是我的答案,而是@JWilliman的答案 - 他们的答案在@Prasad Chalasani的答案评论中。我写这篇文章是因为当前被投票赞同的答案对我来说实际上并没有很好地发挥作用,但是@JWilliman的解决方案确实有效:

#Answer   
+ theme(axis.title.x = element_text(margin = margin(t = 20))

这是因为theme(axis.title.x = element_text(vjust = 0.5))已被取代,现在无论您输入什么值,它都会将标题/标签移动固定的距离。


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