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

ggplot2如何实现自定义坐标轴断点的等距刻度显示

解决方案

你需要为坐标轴自定义非线性转换,让指定断点在视觉上等距,通过scales::trans_new()实现自定义转换即可,修改后代码如下:

library(ggplot2)
library(scales)

# 预定义目标断点及对应等距位置
breaks_vec <- c(0.01, 0.05, 0.2, 0.5, 0.8, 0.95, 0.99)
pos_vec <- seq_along(breaks_vec)

# 自定义坐标轴转换
custom_trans <- trans_new(
  name = "custom",
  # 正向转换:将原始数值映射为等距位置
  transform = function(x) approx(breaks_vec, pos_vec, xout = x)$y,
  # 反向转换:将位置映射回原始数值
  inverse = function(pos) approx(pos_vec, breaks_vec, xout = pos)$y,
  # 断点沿用预设值
  breaks = function(x) breaks_vec
)

sim_df <- data.frame(fpr = seq(0.001, 0.999, 0.001),
                     fnr = rev(seq(0.001, 0.999, 0.001)))

ggplot(sim_df, aes(x = fpr, y = fnr)) +
  geom_line() +
  scale_y_continuous(labels = percent_format(1),
                     trans = custom_trans) +
  scale_x_continuous(labels = percent_format(1),
                     trans = custom_trans) +
  coord_cartesian(xlim = c(0.01, 0.99), ylim = c(0.01, 0.99))

说明

  • 自定义转换通过分段线性插值,将7个预设断点映射到1-7的均匀位置,断点之间的数值也会按照相对位置平滑转换
  • 生成的坐标轴会完全符合等距分布指定刻度的需求,同时保留曲线的正确形状

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:09:03