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

如何在ggplot2坐标轴中显示-Inf(负无穷)符号?

问题:ggplot坐标轴原点显示-Inf符号

我的数据格式如下:

> head(df_x)
      log10.p. log10.q.
1        -Inf       -Inf
2        -Inf       -Inf
3        -Inf       -Inf
4        -Inf       -Inf
5        -Inf       -Inf
6  -0.7940367 -1.3546946

变量原始取值范围是(0,1),经log10转换后范围变为(-Inf, 0),其中-Inf对应log(0)(无定义),log(1)=0。

我用以下代码绘图:

p <- ggplot(df_pq, aes(x = p, y =  q)) + geom_point(colour = "blue") +
     labs(x = expression(log[10](p)), y = expression(log[10](q))) +
     xlim(-Inf, 0) +
     ylim(-Inf, 0)

希望在坐标轴原点位置显示无穷符号(-∞),请问怎么实现?

解决方案

可以通过自定义坐标轴刻度来实现,以下是两种可行方法:

方法1:直接自定义刻度标签与范围

使用scale_x_continuous和scale_y_continuous手动指定刻度位置和标签,把对应-Inf的位置替换为-∞符号:

library(ggplot2)

p <- ggplot(df_pq, aes(x = p, y = q)) + 
  geom_point(colour = "blue") +
  labs(x = expression(log[10](p)), y = expression(log[10](q))) +
  # 自定义x轴刻度
  scale_x_continuous(
    limits = c(-Inf, 0),
    breaks = c(-Inf, -2, -1, 0),  # 可根据数据分布调整中间刻度
    labels = c("-∞", "-2", "-1", "0")
  ) +
  # 自定义y轴刻度
  scale_y_continuous(
    limits = c(-Inf, 0),
    breaks = c(-Inf, -2, -1, 0),
    labels = c("-∞", "-2", "-1", "0")
  )

方法2:替换-Inf为极小值后自定义刻度

如果直接用-Inf在breaks中出现异常,可先将数据中的-Inf替换为一个接近-Inf的极小值(比如-10,根据数据分布调整),再设置刻度:

# 替换数据中的-Inf
df_pq$p[is.infinite(df_pq$p)] <- -10
df_pq$q[is.infinite(df_pq$q)] <- -10

# 绘图并自定义刻度
p <- ggplot(df_pq, aes(x = p, y = q)) + 
  geom_point(colour = "blue") +
  labs(x = expression(log[10](p)), y = expression(log[10](q))) +
  scale_x_continuous(
    limits = c(-10, 0),
    breaks = c(-10, -2, -1, 0),
    labels = c("-∞", "-2", "-1", "0")
  ) +
  scale_y_continuous(
    limits = c(-10, 0),
    breaks = c(-10, -2, -1, 0),
    labels = c("-∞", "-2", "-1", "0")
  )

注:中间刻度(如-2、-1)可根据实际数据分布调整,保证刻度显示合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:40:26