Y 轴标题看起来太靠近轴文本。
ggplot(mpg, aes(cty, hwy)) + geom_point()
我试过用 theme()改变许多参数的值,但似乎都没有帮助。
theme()
从 ggplot2 2.0.0可以使用 element_text()的 margin =参数来更改轴标题和数字之间的距离。在元素的 top、 right、 bottom 和 lleft 端设置 margin的值。
ggplot2 2.0.0
element_text()
margin =
t
r
b
l
margin
ggplot(mpg, aes(cty, hwy)) + geom_point()+ theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin也可以用于其他 element_text元素(参见 ?theme) ,如 axis.text.x、 axis.text.y和 title。
element_text
?theme
axis.text.x
axis.text.y
title
加法
为了设置轴标题的边距,当轴有一个不同的位置(例如,与 scale_x_...(position = "top"),你将需要一个不同的主题设置-例如 axis.title.x.top。参见 https://github.com/tidyverse/ggplot2/issues/4343。
scale_x_...(position = "top")
axis.title.x.top
在 theme函数中使用 vjust是一种解决方案,它比 \n提供更细粒度的控制,但比添加边距更省事。
theme
vjust
\n
为了调整 y 轴或(x 轴)上的位置以增加空间,这通常需要使用 正面价值来表示 vjust(y 轴)或 vjust(x 轴)的负值,就像在 theme(axis.title.y = element_text(vjust = 2))中一样。请参阅下面一个完整的示例。
theme(axis.title.y = element_text(vjust = 2))
# load patchwork to show plots side-by-side library(patchwork) library(ggplot2) # Plot A: just for comparison, moving titles *inward* p1 <- ggplot(mpg, aes(cty, hwy)) + geom_point() + theme_gray() + theme( axis.title.y = element_text(vjust = -3), axis.title.x = element_text(vjust = +3) ) # Plot B: what we want, moving titles *outward* p2 <- ggplot(mpg, aes(cty, hwy)) + geom_point() + theme_gray() + theme( axis.title.y = element_text(vjust = +3), axis.title.x = element_text(vjust = -0.75) ) # show plots side-by-side with patchwork package p1 + p2 + plot_annotation(tag_levels = "A")
基于此论坛帖子: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU
听起来最简单的事情就是在 x 轴之前和 y 轴标签之后添加一个换行符(n)。似乎比上面提到的解决方案要容易得多(尽管比较愚蠢)。
ggplot(mpg, aes(cty, hwy)) + geom_point() + xlab("\nYour_x_Label") + ylab("Your_y_Label\n")
希望能帮上忙!
出于某种原因,迪齐斯 · 埃尔费茨提出的保证金论点对我不起作用。因此,我使用了另一种技巧,它比添加一个空行更灵活,但需要放弃轴的滴答声。
myplot + theme(axis.ticks.x = element_blank(), axis.ticks.length.x = unit(3.25, "cm")
我想,可以使用 geom_segment手动添加刻度标记。另一种可能是 [ggalt::annotation_ticks][1],但是我也没有费心去尝试(注意,CRAN 上的当前版本 ggalt (0.4)不支持这个函数,github 上的 ggalt (0.6)支持)。
geom_segment
[ggalt::annotation_ticks][1]