如何使用hjust调整cowplot::plot_grid中单个子图的标签位置
解决方法
标签错位是因为第二个子图隐藏了y轴文本,两个子图的面板相对位置存在偏差,通过hjust参数统一标签对齐基准即可解决:hjust参数用于控制标签自身的水平对齐规则,取值为0时标签左边缘对齐你指定的label_x坐标,取值为1时右边缘对齐,0.5为居中对齐。你只需要将hjust设为0,再微调label_x的取值,就能保证两个标签的位置完全一致。
调整后的完整代码如下:
library(ggplot2) library(cowplot) # 数据集 riverssub<-structure(list(richness = c(127L, 110L, 89L, 74L, 62L, 18L, 22L, 71L, 38L, 91L, 56L, 39L, 90L, 37L, 147L, 53L, 92L, 207L, 52L, 126L, 79L, 32L, 100L, 181L, 83L, 690L), surface = c(33490, 4410, 770, 164.7, 288.5, 9.85, 33.1, 750, 46.9, 970, 85.2, 39.2, 780, 97.3, 3983.71, 220, 500, 11250, 115, 1350, 278, 23.05, 310, 2050, 560, 34570), disch = c(2640L, 687L, 170L, 353L, 384L, 16L, 31L, 513L, 32L, 392L, 50L, 32L, 206L, 81L, 1260L, 104L, 220L, 6100L, 308L, 2060L, 443L, 102L, 348L, 4758L, 913L, 40487L)), class = "data.frame", row.names = c(NA, -26L)) # 绘制单图 a <- ggplot(data = riverssub, aes(x = surface , y = richness)) + geom_point() + scale_y_log10() + scale_x_log10() + labs(x='Surface Area (100 km²)', y="Fish Species Richness") + theme_bw() b <- ggplot(data = riverssub, aes(x = disch , y = richness)) + geom_point() + scale_y_log10() + scale_x_log10() + labs(x=bquote('Mean Annual Discharge'~(m^3 * s^-1)), y=" ") + theme_bw() # 拼接多图,新增hjust=0参数 plot_grid(a, b + theme(axis.text.y = element_blank()), nrow = 1, align = 'h', labels="AUTO", label_y=0.97, label_x=0.03, hjust = 0)
如果调整后还有轻微偏差,也可以给label_x传递长度为2的向量,分别自定义两个标签的水平位置,比如label_x = c(0.03, 0.02),适配你的画布尺寸。
内容的提问来源于stack exchange,提问作者Jordan Woolfrey
相关产品推荐
相关产品推荐

