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

如何通过ggplot命令避免cut生成的bins图例出现科学计数法

问题:仅通过修改ggplot代码避免bins图例显示科学计数法

我的数据样本:

> head(sample, 10)
   variable longitude latitude value
1         A      8.43    49.42  1000
2         B      8.92    49.14  2000
3         C      8.53    49.43  3000
4         D     12.25    50.32  4000
5         A     13.86    51.47  5000
6         B      9.01    51.38  6000
7         C      8.18    51.25  7000
8         D      7.66    51.30  8000
9         A     11.99    50.58  9000
10        B     12.15    50.92 10000

已创建断点分组:

brks <- c(0, 2000, 4000, 6000, 8000, 10000)
sample <- mutate(sample, bins = cut(value, breaks = brks, right = TRUE))

当前ggplot绘图代码:

ggplot() +
  geom_point(data = sample, aes(x = longitude, y = latitude, size = bins, color = variable)) 

需求:不想修改cut命令(已知加dig.lab参数可解决),仅调整ggplot代码让bins图例不显示科学计数法,options('scipen')无效。


解决方案

可以通过自定义图例标签的方式在ggplot中实现,以下是几种可行方法:

方法1:用scale_size_discrete自定义标签解析逻辑

提取bins的水平值,将其中的科学计数法格式转换为常规数字格式:

ggplot() +
  geom_point(data = sample, aes(x = longitude, y = latitude, size = bins, color = variable)) +
  scale_size_discrete(
    labels = function(x) {
      sapply(strsplit(x, "\\(|,|\\]"), function(y) {
        # 提取区间两端的数字,转为常规格式后拼接
        paste0(format(as.numeric(y[2]), scientific = FALSE), 
               " - ", 
               format(as.numeric(y[3]), scientific = FALSE))
      })
    }
  )

方法2:在aes内重新定义bins的标签

无需修改原始数据框,直接在绘图映射中重新生成无科学计数法的因子标签:

ggplot() +
  geom_point(
    data = sample,
    aes(
      x = longitude, 
      y = latitude, 
      size = factor(bins, 
                   labels = sapply(levels(sample$bins), function(l) {
                     # 匹配区间内的数字并格式化
                     nums <- as.numeric(regmatches(l, gregexpr("[0-9.e+]+", l))[[1]])
                     paste(format(nums[1], scientific = FALSE), "-", format(nums[2], scientific = FALSE))
                   })), 
      color = variable
    )
  ) +
  labs(size = "Bins")  # 保持图例标题与原设定一致

方法3:借助scales包的格式化函数

用scales包的label_number()函数更优雅地处理数字格式:

library(scales)

ggplot() +
  geom_point(data = sample, aes(x = longitude, y = latitude, size = bins, color = variable)) +
  scale_size_discrete(
    labels = function(x) {
      lapply(strsplit(x, "\\(|,|\\]"), function(y) {
        paste(label_number()(as.numeric(y[2])), "-", label_number()(as.numeric(y[3])))
      })
    }
  )

以上方法均无需修改原始的cut命令,仅通过调整ggplot代码即可让图例显示常规数字格式,避免科学计数法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:07:27