Adding a comma and a plus sign (+) to numbers on the x axis of ggplot

I have plotted the following figure, which shows numbers on the x axis. What I want is to add commas and plus signs on these numbers. What I would expect is "+100,000" or "+200,000". Nonetheless, I have only managed to do it separately, as: "100,000" or "+100000" Figure

I used the following code.

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 = function(x) sprintf("%+d", x)) +
  scale_y_continuous(labels = function(y) sprintf("%+d", y))

I know the code to add the comma is scale_x_continuous(labels = comma) but I don't know to add it to my previous code.

Upvotes: 2

Views: 1390

Answers (1)

Bruno
Bruno

Reputation: 4150

EDIT: Use up-to-date functions (2024)

The scales package covers this use case.

e.g

scales::label_number(style_positive = c("plus"), big.mark = ",")(1000)

Using it in your code:

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 = scales::label_number(style_positive = c("plus"), big.mark = ",")) +
  scale_y_continuous(
    labels = label_number(style_positive = c("plus"), big.mark = ","))

Upvotes: 2

Related Questions