使用scale_fill_gradientn长图例名及cowplot时图例框偏移的修复方法
解决cowplot添加内嵌图后地图图例偏移的问题
当使用cowplot::ggdraw()为地图主图添加内嵌图时,原本设置在底部居中的图例会出现偏移。这是因为ggdraw()的绘图空间逻辑与ggplot原生布局冲突,导致图例的自动居中定位失效。
以下是两种可行的修复方案:
方案一:提取图例,用plot_grid组合布局
这种方法通过拆分主图、内嵌图和图例,再重新组合,确保图例稳定居中:
library(ggplot2) library(dplyr) library(sf) library(cowplot) nc <- st_read(system.file("shape/nc.shp", package="sf")) # 生成带完整图例设置的主图 mainplot <- nc %>% ggplot() + geom_sf(aes(fill = AREA)) + scale_fill_gradientn(name="A fairly long legend title just for illustration!!!!", colors = RColorBrewer::brewer.pal(9, "Spectral") %>% rev()) + guides(fill = guide_colorbar(title.position = "top", title.hjust = 0.5, barwidth = 8, barheight = 1)) + theme(legend.direction = "horizontal", legend.position = "bottom") # 单独提取图例组件 legend <- get_legend(mainplot) # 生成不带图例的主图版本 mainplot_no_legend <- mainplot + theme(legend.position = "none") # 给无图例主图添加内嵌图 main_with_inset <- ggdraw(mainplot_no_legend) + draw_plot(ggplot(nc) + geom_histogram(aes(AREA)) + theme_cowplot(12), x = .04, y = .25, width = .25, height = .2) # 垂直组合带内嵌图的主图和图例,设置高度比例 final_plot <- plot_grid(main_with_inset, legend, ncol = 1, rel_heights = c(1, 0.1)) print(final_plot)
方案二:手动在ggdraw中定位图例
如果希望直接在ggdraw的绘图框架内调整图例位置,可以手动添加提取出的图例,指定底部居中的坐标:
library(ggplot2) library(dplyr) library(sf) library(cowplot) nc <- st_read(system.file("shape/nc.shp", package="sf")) mainplot <- nc %>% ggplot() + geom_sf(aes(fill = AREA)) + scale_fill_gradientn(name="A fairly long legend title just for illustration!!!!", colors = RColorBrewer::brewer.pal(9, "Spectral") %>% rev()) + guides(fill = guide_colorbar(title.position = "top", title.hjust = 0.5, barwidth = 8, barheight = 1)) + theme(legend.direction = "horizontal", legend.position = "bottom") # 提取图例 legend <- get_legend(mainplot) # 主图移除图例,添加内嵌图,再手动放置图例到底部居中区域 final_plot <- ggdraw(mainplot + theme(legend.position = "none")) + draw_plot(ggplot(nc) + geom_histogram(aes(AREA)) + theme_cowplot(12), x = .04, y = .25, width = .25, height = .2) + draw_plot(legend, x = 0.15, y = 0.02, width = 0.7, height = 0.1) print(final_plot)
说明
- 方案一的优势在于布局自动对齐,无需手动调整参数,适合批量绘图场景;
- 方案二需要微调
x、y、width、height参数,适合需要更精细化布局控制的场景。
内容的提问来源于stack exchange,提问作者rez
相关产品推荐
相关产品推荐

