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

如何为ggplot温度超限图设置分段坐标轴(0-10对数,11-100线性)

解决ggplot混合对数-线性X轴刻度问题

要实现0-10区间对数刻度、11-100区间线性刻度,且指定刻度值,核心是创建自定义坐标转换函数,替代全局对数刻度。以下是具体实现:

步骤1:定义自定义转换规则

使用scales包的trans_new函数,分别处理两段区间的坐标转换:

  • 0-10区间:用log10(x+1)避免x=0时的对数无意义问题,实现对数映射
  • 10-100区间:以10对应的对数转换值为起点,用线性映射让刻度间距均匀
library(scales)
# 创建自定义转换函数
custom_log_linear <- trans_new(
  name = "log_linear",
  # 正向转换:原始x → 绘图坐标
  transform = function(x) {
    log10_11 <- log10(11)  # 10对应的转换值
    ifelse(x <= 10, 
           log10(x + 1),  # 0→0,10→log10(11)≈1.041
           log10_11 + (x - 10)/10)  # 10→1.041,25→2.541,100→10.041
  },
  # 反向转换:绘图坐标 → 原始x(用于交互或坐标轴计算)
  inverse = function(x) {
    log10_11 <- log10(11)
    ifelse(x <= log10_11,
           10^x - 1,
           10 + (x - log10_11)*10)
  }
)

步骤2:应用到你的绘图代码

修改原有的scale_x_continuous,使用自定义转换并指定需要的刻度值:

set.seed(123)
n <- 500
x <- seq(0, 100, length.out = n)
y <- 16 / (1 + exp(-0.2 * (x - 50))) - 8
data <- data.frame(x = x, y = y)

G1 <- ggplot(data, aes(x = x, y = y)) +
  geom_line() + 
  theme(axis.line = element_line(size = 1, color = "black")) +
  geom_hline(yintercept = 0, lty = "dashed") +
  # 应用自定义转换,指定刻度和标签
  scale_x_continuous(
    trans = custom_log_linear,
    breaks = c(0, 5, 10, 25, 50, 75, 100),
    expand = expand_scale(mult = c(0.01, 0.01))
  ) +
  theme(legend.position = "none",
        axis.title.x = element_blank(),
        axis.title.y = element_blank())

print(G1)

为什么原代码有问题?

你之前用scale_x_log10会把整个X轴设为对数刻度:

  • 对数轴上,10到100的区间仅对应log10(10)=1到log10(100)=2的范围,视觉上占比极小,导致刻度挤在一起
  • 自定义转换拆分了区间,让10-100部分用线性映射,保证刻度间距均匀

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:23:28