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

如何在R中使用ggplot调整哑铃图的y轴间距并自定义排序

问题解决方法

1. 调整Y轴分类按lower数值排序

ggplot的分类轴默认按因子的字母顺序排序,你只需要将loc列转为按lower值排序的因子即可,用reorder()函数可以快速实现:

# 将loc转为按lower升序排列的因子,要降序的话给第二个参数加负号即可
df$loc <- reorder(df$loc, df$lower)

2. 解决Y轴标签重叠问题,可按需选择以下方案:

  • 方案1:调整输出图表的高度,高度越高单个分类的预留间距越大
    绘图完成后用ggsave保存时指定高度参数即可,示例:
    # 可以根据分类数量调整height数值,分类越多height设得越大
    ggsave("range_plot.png", plot = last_plot(), width = 7, height = 12, dpi = 300)
    
    如果你在RStudio中预览,直接手动拉大绘图面板的高度也能直接看到效果。
  • 方案2:缩小Y轴标签的字号
    在ggplot代码中添加theme配置调整y轴文本大小:
    ggplot(df) +
      geom_point(aes(lower, loc), color = "Blue") + 
      geom_point(aes(upper, loc), color = "Red") +
      geom_segment(aes(x = lower, y = loc, xend = upper, yend = loc)) +
      # 调整y轴文本字号,可按需调整size数值
      theme(axis.text.y = element_text(size = 8))
    
  • 方案3:如果分类数量极多,可选择将标签横向排布
    给y轴文本设置旋转角度和对齐方式:
    theme(axis.text.y = element_text(size = 8, angle = 0, hjust = 1))
    

完整可运行的修正代码(修复原代码中loc向量漏写逗号的问题)

library(ggplot2)
lower = c(83, 81, 80, 71, 69, 63, 63, 62, 54)
upper = c(112, 96, 111, 141, 125, 89, 178, 107, 130)
# 原代码ANG MO KIO后漏了逗号,此处已补全
loc = c("YISHUN", "WOODLANDS", "HOUGANG", "ANG MO KIO", "TAMPINES", "SENGKANG", "GEYLANG", "BEDOK", "JURONG WEST")
df = data.frame(lower, upper, loc)
# 按lower值排序y轴分类
df$loc <- reorder(df$loc, df$lower)

ggplot(df) +
  geom_point(aes(lower, loc), color = "Blue") + 
  geom_point(aes(upper, loc), color = "Red") +
  geom_segment(aes(x = lower, y = loc, xend = upper, yend = loc)) +
  # 按需调整y轴文本样式
  theme(axis.text.y = element_text(size = 9))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:45:04