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

R语言实现自定义非线性连续轴缩放:消除间断轴分块留白

核心实现方案

直接通过ggplot原生的自定义坐标轴变换实现要求的分段高度映射,完全替代多图拼接逻辑,从根源消除面板间隙、边缘截断、轴间断的问题。

实现原理

你设定的高度-数值映射规则可以直接写成连续的分段变换函数,不需要拆成3个独立绘图面板拼接:

  • 绘图区最下方50%的垂直高度:映射数值范围1-200
  • 绘图区中间30%的垂直高度:映射数值范围201-1000
  • 绘图区最上方20%的垂直高度:映射数值范围1001-40000
    这种方式生成的图表是单面板连续坐标系,不存在任何拼接留白、轴间断问题。

完整可运行代码

# 加载依赖包
library(tidyverse)
library(scales)

# 生成和你完全一致的模拟数据集
set.seed(1)
graphdata <- as.data.frame(rlnorm(29000, meanlog = 4.442651, sdlog = 0.85982))
colnames(graphdata)[1] <- "values"
high_values <- as.data.frame(rlnorm(1000, meanlog = 9.9, sdlog = 0.85))
colnames(high_values)[1] <- "values"
graphdata <- rbind(graphdata, high_values)
graphdata$values <- round(graphdata$values, digits = 0)

# 定义符合高度映射规则的自定义坐标轴变换
custom_trans <- trans_new(
  name = "custom_segment",
  # 正变换:将原始数值映射为绘图区的相对垂直位置(0=最底部,1=最顶部)
  transform = function(x) {
    case_when(
      x <= 200 ~ 0.5 * (x - 14) / (200 - 14),
      x <= 1000 ~ 0.5 + 0.3 * (x - 201) / (1000 - 201),
      TRUE ~ 0.8 + 0.2 * (x - 1001) / (40001 - 1001)
    )
  },
  # 反变换:将绘图区的相对垂直位置还原为原始数值,保证刻度、数据点定位准确
  inverse = function(x_trans) {
    case_when(
      x_trans <= 0.5 ~ 14 + x_trans / 0.5 * (200 - 14),
      x_trans <= 0.8 ~ 201 + (x_trans - 0.5) / 0.3 * (1000 - 201),
      TRUE ~ 1001 + (x_trans - 0.8) / 0.2 * (40001 - 1001)
    )
  }
)

# 最终绘图,无拼接、无间隙
ggplot(graphdata, aes(y = values, x = 1)) +
  geom_jitter(aes(colour = cut(values, c(0, 100, 200, Inf))), alpha = 0.2, size = 0.5) +
  scale_color_manual(values = c("#F0CF19", "#F07C0B", "#D52828")) +
  scale_y_continuous(
    breaks = c(20, 50, 100, 200, 500, 1000, 10000, 20000, 40000),
    trans = custom_trans,
    limits = c(14, 40001),
    expand = c(0, 0)
  ) +
  labs(y = "Values", x = NULL) +
  scale_x_continuous(expand = c(0.01, 0)) +
  coord_cartesian(clip = "off") +
  theme_classic() +
  theme(
    legend.position = "none",
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    axis.line.x = element_blank()
  )

方案优势

  • 单连续绘图面板,不存在任何面板间隙、轴间断,完全符合你要求的高度占比映射规则
  • 所有数据点统一在同一坐标系下计算位置,不会出现多图拼接时的边缘截断半圆点问题
  • 调整灵活:如果后续需要修改每个数值区间对应的高度占比,只需要修改custom_trans里的系数即可,不需要重新调整多图拼接的边距、对齐逻辑
  • 坐标轴刻度完全按照原始数值标注,不会出现拼接时各面板独立刻度对齐错位的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 16:45:07