如何缩小ggplot2极坐标图周围及分面标题的间距?
解决ggplot2极坐标环形图分面标题间距过大问题
问题描述
基于R Graph Gallery的环形图示例添加facet_wrap分面后,分面标题与极坐标图间距过远,且图表周围冗余空间过大。查阅Stack Overflow相关内容后仍未解决,原代码及无效尝试如下:
原代码
library(ggplot2) data <- data.frame( category = c("A", "B", "C"), ymax = c(0.1, 0.7, 1.0), ymin = c(0.0, 0.1, 0.7), facet = rep("Label", 3) ) # 绘制图表 ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) + geom_rect() + scale_fill_brewer(palette=4) + coord_polar(theta="y") + xlim(c(2, 4)) + theme_void() + theme(legend.position = "none") + facet_wrap(~facet)
无效尝试代码
ggplot(...) + geom_hline(yintercept = seq(0, 1, by = 0.25), colour = "grey90", size = 0.2) + theme(panel.grid = element_blank())
解决方案
通过调整x轴范围减少图表周围冗余空间,同时修改分面标题的边距参数拉近标题与图表的距离,具体代码如下:
library(ggplot2) data <- data.frame( category = c("A", "B", "C"), ymax = c(0.1, 0.7, 1.0), ymin = c(0.0, 0.1, 0.7), facet = rep("Label", 3) ) ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) + geom_rect() + scale_fill_brewer(palette=4) + coord_polar(theta="y") + xlim(c(2.5, 4)) # 缩小左侧空白区域,减少整体冗余空间 theme_void() + theme( legend.position = "none", # 调整分面标题的下边距,负数表示拉近与图表的距离 strip.text = element_text(margin = margin(b = -15, unit = "pt")) ) + facet_wrap(~facet)
补充说明
- 调整
xlim的左边界值:如果觉得环形内圈太小,可在2.5到3之间微调,平衡内圈空白和整体空间。 - 调整
margin(b = -15)的数值:根据实际图表大小增减负数绝对值,直到标题位置符合预期。 - 若仍有整体边距问题,可添加
plot.margin = margin(5, 5, 5, 5, "pt")到theme中,进一步缩小图表整体边距。
内容的提问来源于stack exchange,提问作者Majid Zaremehrjardy
相关产品推荐
相关产品推荐

