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))
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.
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.
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).
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.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With