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

R语言ggplot如何为坐标轴数值同时添加千分位逗号和正负号

解决方案

你可以通过以下两种方式实现x、y轴刻度同时显示正负号和千分位逗号:

方法一:使用scales包的label_comma函数(推荐)

首先确保你已经加载了scales包:

library(scales)

将原代码中scale_x_continuous和scale_y_continuous的labels参数替换为label_comma(style_positive = "plus")即可,修改后的对应代码段如下:

scale_x_continuous(labels = label_comma(style_positive = "plus")) +
scale_y_continuous(labels = label_comma(style_positive = "plus"))

该函数会自动处理正负号显示:正数前加+,负数前保留-,同时自动添加千分位逗号。

方法二:自定义格式化函数(适配旧版本scales包)

如果你的scales包版本较低不支持style_positive参数,可以自定义格式化函数实现效果:

scale_x_continuous(labels = function(x) paste0(ifelse(x > 0, "+", ""), comma(x))) +
scale_y_continuous(labels = function(y) paste0(ifelse(y > 0, "+", ""), comma(y)))

修改后完整代码示例

library(ggplot2)
library(scales)
library(ggpubr) # 对应你用到的stat_cor函数

ggplot(data, aes(x = difference_gdp, y = difference_rate, color = region)) +  
  geom_point(size = 4) + 
  xlab("Variation in GDP per capita, 1990 vs 2019")  + 
  ylab("Variation in age-standardised\nT2DM-attributable deaths per\n100,000 people, 1990 vs 2019") +
  stat_cor(method = "pearson", aes(x=difference_gdp, y = difference_rate, color = NA), digits = 2, p.accuracy = 0.05) +   
  geom_smooth(method = 'lm', formula = 'y~x', se = FALSE, aes(color = NA)) + 
  scale_x_continuous(labels = label_comma(style_positive = "plus")) +
  scale_y_continuous(labels = label_comma(style_positive = "plus"))

内容的提问来源于stack exchange,提问作者Wilmer Cristobal Guzman-Vilca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:39:02