R语言ggiraph包拼接图表输出时如何增大地图宽度
问题描述
运行以下R代码绘制交互式联动图表时,需要增大输出结果中地图模块的宽度,原代码如下:
library(tidycensus) library(ggiraph) library(tidyverse) library(patchwork) library(scales) vt_income <- get_acs( geography = "county", variables = "B19013_001", state = "VT", year = 2020, geometry = TRUE ) %>% mutate(NAME = str_remove(NAME, " County, Vermont")) vt_map <- ggplot(vt_income, aes(fill = estimate)) + geom_sf_interactive(aes(data_id = GEOID)) + scale_fill_distiller(palette = "Greens", direction = 1, guide = "none") + theme_void() vt_plot <- ggplot(vt_income, aes(x = estimate, y = reorder(NAME, estimate), fill = estimate)) + geom_errorbar(aes(xmin = estimate - moe, xmax = estimate + moe)) + geom_point_interactive(color = "black", size = 4, shape = 21, aes(data_id = GEOID)) + scale_fill_distiller(palette = "Greens", direction = 1, labels = label_dollar()) + scale_x_continuous(labels = label_dollar()) + labs(title = "Household income by county in Vermont", subtitle = "2016-2020 American Community Survey", y = "", x = "ACS estimate (bars represent margin of error)", fill = "ACS estimate") + theme_minimal(base_size = 14) girafe(ggobj = vt_map + vt_plot, width_svg = 10, height_svg = 5) %>% girafe_options(opts_hover(css = "fill:cyan;"))
解决方案
代码用patchwork包拼接地图和点图两个子模块,默认两个子模块宽度占比为1:1,调整地图宽度只需要在拼接子图时调用plot_layout()函数,通过widths参数自定义两个模块的宽度比例即可:
widths接收长度为2的数值向量,第一个值对应地图的宽度权重,第二个值对应右侧点图的宽度权重,数值越大对应模块占总宽度的比例越高。比如设置widths = c(1.5, 1)就代表地图宽度是点图的1.5倍,设置widths = c(2,1)代表地图占2/3总宽度、点图占1/3,可按需调整数值。- 如果需要调整整个交互图的总宽度,同步修改
girafe()中的width_svg参数即可。
修改后的核心输出代码如下:
# 此处以地图宽度为点图1.2倍、总svg宽度11为例,可自行调整参数 girafe(ggobj = vt_map + vt_plot + plot_layout(widths = c(1.2, 1)), width_svg = 11, height_svg = 5) %>% girafe_options(opts_hover(css = "fill:cyan;"))
内容的提问来源于stack exchange,提问作者Meo
相关产品推荐
相关产品推荐

