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

如何在R ggplot斜率图中为重复值设置唯一点位置

斜率图点重叠解决与标签添加方案

要解决同值点重叠问题,同时实现侧边带国家标签的斜率图效果,可通过位置偏移结合智能标签定位实现,完整代码如下:

library(tidyverse)
library(ggrepel) # 用于自动避免标签重叠

# 数据预处理:将年份转为因子,确保x轴顺序正确
tax_long <- tax |>
  pivot_longer(
    cols = c("1970", "1979"),
    names_to = "Year",
    values_to = "Tax"
  ) |>
  mutate(Year = factor(Year, levels = c("1970", "1979")))

# 绘制斜率图
ggplot(tax_long, aes(x = Year, y = Tax, group = Country)) +
  # 绘制国家间的连线
  geom_line(color = "gray50", linewidth = 0.8) +
  # 绘制散点,用position_dodge错开同值点
  geom_point(aes(color = Country), size = 3, 
             position = position_dodge(width = 0.1)) +
  # 添加1970年的国家标签(左侧对齐)
  geom_text_repel(
    data = filter(tax_long, Year == "1970"),
    aes(label = Country),
    hjust = 1.1,
    direction = "y",
    size = 3.5,
    color = "black"
  ) +
  # 添加1979年的国家标签(右侧对齐)
  geom_text_repel(
    data = filter(tax_long, Year == "1979"),
    aes(label = Country),
    hjust = -0.1,
    direction = "y",
    size = 3.5,
    color = "black"
  ) +
  # 扩展x轴空间,避免标签被截断
  scale_x_discrete(expand = expansion(add = c(2, 2))) +
  # 主题美化
  theme_minimal() +
  theme(
    legend.position = "none",
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank(),
    axis.title = element_text(size = 11),
    plot.title = element_text(size = 14, hjust = 0.5)
  ) +
  labs(
    x = "年份",
    y = "税收占比(%)",
    title = "1970-1979年各国税收占比变化"
  )

核心处理逻辑

  • position_dodge(width = 0.1):让同一y值的点在x轴方向轻微偏移,既解决重叠问题,又不会破坏国家连线的对应关系。
  • geom_text_repel:自动调整标签位置避免重叠,通过hjust参数控制标签在散点外侧(1970年左移、1979年右移),保证图表整洁。
  • scale_x_discrete(expand = ...):扩展x轴左右两侧的空间,防止国家标签被图表边缘截断。

如果不想依赖ggrepel包,也可以用基础的geom_text,但需要手动调整标签位置,标签重叠的概率会更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:20:10