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

求助:ggplot中如何用1/10^x公式转换y轴次坐标轴?

解决ggplot次坐标轴1/10^x转换问题

以下是修改后的可运行代码,实现次坐标轴显示1/10^br对应数值的需求:

x <- as.factor(c(1,2,3,1,2,3,1,2,3,1,2,3))
y <- c(0.0541, 0.0706, 0.4803, 0.0151, 0.0729, 0.0689, 0.0986, 0.1949, 0.3323, 0.5166, 0.0988, 0.2321)
grupo <- as.factor(c(1,1,1,2,2,2,3,3,3,4,4,4))
br <- c(0,0.1, 0.2,0.3,0.4, 0.5, 0.6, 0.7)

df <- data.frame(x =x ,y = y, gr = grupo)

library(ggplot2)
library(scales)

ggplot() +
  geom_point(data=df, aes(x=x, y=y, group=gr, color= gr, shape= gr))+
  geom_line(data=df, aes(x=x, y=y, group=gr, color= gr ))+
  scale_y_reverse(limits = c(0.7, -0.05), breaks = br,
                  sec.axis = sec_axis(
                    trans = ~10^(-.),  # 主轴值转次轴值:1/10^x
                    breaks = 10^(-br), # 次轴刻度与主轴br一一对应
                    labels = label_number(accuracy = 0.001) # 调整标签显示精度
                  ))

关键修改说明:

  • sec_axis的trans参数:使用~10^(-.)实现主轴值到1/10^x的转换,其中.代表主轴的数值。
  • breaks参数:手动计算次轴刻度为10^(-br),确保和主轴刻度完全对应。
  • labels参数:借助scales::label_number调整标签精度,避免科学计数法或小数位数不足的问题。

内容的提问来源于stack exchange,提问作者Aurora González-Vidal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:50:26