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

如何将R语言ggplot绘图的Y轴标签设置为10^n格式的指数标注

你只需在scale_y_continuous配置中添加自定义labels参数,将断点数值转换为可解析的幂次表达式即可实现需求,具体修改如下:

首先提前加载必要的依赖包:

library(ggplot2)
library(scales)
library(ggh4x)

核心改动是在scale_y_continuous中新增labels = ~ parse(text = paste0("10^", log10(.x)))配置,修改后的完整绘图代码如下:

ggplot(bar, aes(pos,val, fill = group)) +
  geom_bar(stat = 'identity', width = 1) + 
  scale_y_continuous(trans=scales::pseudo_log_trans(base = 10),
                     breaks=c(1, 10, 100, 1000, 10000, 100000),
                     labels = ~ parse(text = paste0("10^", log10(.x))),
                     expand = c(0, 0),
  ) +
  scale_x_continuous(
    minor_breaks = seq(0, 100, by = 20),
    breaks = seq(0, 100, by = 20), limits = c(0, 100),
    expand = expansion(mult = c(0, 0)),
    guide = "axis_minor"
  ) +
  guides(x.sec = "axis_minor", y.sec = "axis_minor") +
  scale_fill_manual(values = alpha(c("grey", "red"), .3)) +
  theme_bw() +
  theme(
    panel.border = element_rect(colour = "black", fill=NA, size=1),
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.text.x.top = element_blank(),
    axis.text.y.right = element_blank()
  ) +
  annotation_logticks(sides = "lr") 

实现原理:上述配置中~是匿名函数简写,.x对应你预先设置的每个Y轴断点数值,log10(.x)会计算得到对应10的指数值,最后用parse()把拼接好的幂次字符串转为R绘图可识别的表达式,即可自动渲染出上标格式的10^n标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:45:03