You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何减少ggplot2环形图(Donut Chart)的空白区域

解决ggplot2环形图的多余空白问题

你的环形图出现大量空白,主要是因为xlim设置的范围过宽,加上ggplot默认的绘图边距,以及极坐标转换后的坐标适配问题。以下是几种实用的解决办法:

1. 精准压缩x轴范围

原来的xlim(c(-1, 2.5))给左侧预留了过多空间(因为中心文字用了x=-1),可以把中心文字的x坐标调整到0附近,同时缩小x轴范围,减少无效空白:

library(ggplot2)

test_data <- data.frame(Test = 1:4, Freq = c(0.1, 0.2, 0.3, 0.4))

ggplot(test_data, aes(x = 2, y = Freq, fill = Test)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y", start = 0) +
  theme_void() +
  xlim(c(0, 2.2)) +
  annotate(geom = "text", x = 0, y = 0, label = "Test", size = 60/.pt) +
  theme(
    legend.position = "none",
    plot.background = element_rect(color="red", linewidth = 2),
    plot.margin = margin(0, 0, 0, 0)
  )

2. 彻底清除绘图边距

通过theme的plot.margin参数把四周边距设为0,配合x轴范围调整,能最大程度减少空白:

ggplot(test_data, aes(x = 2, y = Freq, fill = Test)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y", start = 0) +
  theme_void() +
  xlim(c(0, 2.2)) +
  annotate(geom = "text", x = 0, y = 0, label = "Test", size = 60/.pt) +
  theme(
    legend.position = "none",
    plot.background = element_rect(color="red", linewidth = 2),
    plot.margin = margin(t = 0, r = 0, b = 0, l = 0, unit = "pt")
  )

3. 导出图片时匹配宽高比

如果保存图片时仍有空白,用ggsave指定正方形的宽高(环形图是圆形,正方形适配最佳),避免额外留白:

ggsave("donut_plot.png", width = 6, height = 6, units = "in", dpi = 300)

核心思路就是:缩小不必要的坐标范围,清除默认边距,导出时匹配图形比例,就能有效消除环形图周围的大量空白。

内容的提问来源于stack exchange,提问作者Stefan Jelkovich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 07:30:04