Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print positive numbers with plus sign

Tags:

r

ggplot2

I am calculating the difference between years and a reference year. I'd like to use the result as the x-values in a plot. But how can I print a + sign with the positive numbers (-2, -1, 0, +1, +2)?

dat <- data.frame(year = c(2000, 2001, 2002, 2003, 2004), ref = rep(2002)) 
dat$diff <- dat$year - dat$ref

ggplot(dat, aes(x = diff))
like image 490
erc Avatar asked May 19 '16 13:05

erc


People also ask

How do you make positive numbers have a plus sign in Excel?

In the Format Cells window, (1) go to the Number tab and (2) choose the Custom category. In the Type box, (3) enter +0;-0;0. (4) Click OK. All positive numbers now have a plus sign in front of them.

How do you make a plus in Excel?

For simple formulas, simply type the equal sign followed by the numeric values that you want to calculate and the math operators that you want to use — the plus sign (+) to add, the minus sign (-) to subtract, the asterisk (*) to multiply, and the forward slash (/) to divide.

How do you insert a plus or minus sign in Excel?

You can also use the insert Symbol tool. As shown below in the INSERT ribbon (1), you can click on Symbol (2), then make sure you are on the Symbol font (3) (note there are also others) and about 60% down (4) you will see the plus minus symbol (5).

What does clicking the plus sign in Excel do?

Click the minus sign, the selected rows or column are hidden immediately. And click the Plus sign, the hidden rows or columns are showing at once.


2 Answers

You could do

library(ggplot2)
dat <- data.frame(year = c(2000, 2001, 2002, 2003, 2004), ref = rep(2002)) 
dat$diff <- dat$year - dat$ref
ggplot(dat, aes(x = diff)) + 
  scale_x_continuous(labels = function(x) sprintf("%+d", x))
like image 143
lukeA Avatar answered Oct 01 '22 05:10

lukeA


This can also be accomplished with the obscure symnum function and the trusty paste0. Here, 0 does not get a "+" prepended to it.

ggplot(dat, aes(x = diff)) + 
   scale_x_continuous(labels = function(x) paste0(symnum(x, c(-Inf, 0, Inf), c("", "+")), x))
like image 35
lmo Avatar answered Oct 01 '22 05:10

lmo