R ggplot:调整底部单行分箱变量图例的分箱大小与标签布局
解决ggplot离散变量底部单行图例的分箱大小与标签拥挤问题
你可以通过以下两种方式解决当前的图例问题:
方法1:统一图例分箱大小,优化标签布局
通过guide_legend()中的keywidth和keyheight参数固定分箱的宽高,同时调整分箱间距与标签对齐方式,避免拥挤:
shp |> ggplot() + geom_sf(aes(fill = discrete_var)) + scale_fill_brewer(palette = 'Purples', direction = -1, na.value="grey", drop=FALSE) + coord_sf(expand = FALSE) + theme( legend.position = "bottom", legend.spacing.x = unit(0.5, "cm") # 调整分箱之间的水平间距 ) + guides( fill = guide_legend( nrow = 1, byrow = TRUE, label.position = "bottom", keywidth = unit(1.2, "cm"), # 固定分箱宽度 keyheight = unit(0.8, "cm"), # 固定分箱高度 label.hjust = 0.5 # 标签居中对齐 ) )
方法2:旋转标签为垂直排列,避免拥挤
如果标签文本较长,可将标签旋转90度垂直显示,配合调整标签与分箱的间距:
shp |> ggplot() + geom_sf(aes(fill = discrete_var)) + scale_fill_brewer(palette = 'Purples', direction = -1, na.value="grey", drop=FALSE) + coord_sf(expand = FALSE) + theme( legend.position = "bottom", legend.text = element_text(angle = 90, vjust = 0.5) # 旋转标签90度并垂直居中 ) + guides( fill = guide_legend( nrow = 1, byrow = TRUE, label.position = "bottom", keywidth = unit(1, "cm"), label.vjust = 1 # 调整标签与分箱的垂直间距 ) )
内容的提问来源于stack exchange,提问作者MoonS
相关产品推荐
相关产品推荐

