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

如何在RStudio的ggplot中对X轴分组,避免国家标签重复与重叠?

解决ggplot柱状图国家标签重复、柱子重叠问题

问题根源

你设置的position_dodge(3.5)和geom_col(width = 4)参数数值过大,远超X轴分类的默认间距,导致柱子被过度分散,迫使X轴重复显示国家标签,同时柱子出现重叠。

修正步骤

  1. 确保数据格式合法:原样本数据中的字符串值需添加引号,构建标准数据框:
access_plot <- data.frame(
  country = c("benin", "benin", "benin", "burkina faso", "burkina faso", "burkina faso"),
  population = c("rural", "urban", "total", "rural", "urban", "total"),
  percent = c(70, 80, 75, 60, 70, 65)
)
  1. 调整ggplot参数:让position_dodge的宽度与柱子宽度匹配(数值控制在1以内,贴合X轴分类默认间距),同时将数据和全局映射统一放在ggplot()函数中:
ggplot(access_plot, aes(x = country, y = percent, fill = population)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  labs(
    title = "各国不同人口群体用水普及率",
    x = "国家",
    y = "普及率(%)",
    fill = "人口群体"
  )

效果说明

调整后,每个国家的X轴标签仅显示一次,对应rural/urban/total三类柱子会紧凑并排展示,不会出现重叠或标签重复的问题。

内容的提问来源于stack exchange,提问作者Angela G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:07:44