R and ggplot2: Make zero print as “0”

The aesthetics of R printing zeros with superfluous decimal places (e.g. “0.00” instead of “0”) has always bothered me. I also want to keep the number of decimal places for the other ticks consistent (e.g. “0, 0.5, 1.0,” not “0, 0.5, 1”). I could get prettyNum() to fix the “0” instead of “0.0”, but then it was also giving me “1” instead of “1.0”.

It’s possible to get the desired output, for an arbitrary number of decimal places, without resorting to manually defining the break labels. We first define a function to format the labels how we want, using formatC(). We then supply it to the “labels” argument of scale_*_continuous, which takes the original numeric values calculated for the breaks, and applies the function to them.

# Make zeros print as "0" always
prettyZero <- function(l){
	max.decimals = max(nchar(str_extract(l, "\\.[0-9]+")), na.rm = T)-1
	lnew = formatC(l, replace.zero = T, zero.print = "0",
		digits = max.decimals, format = "f", preserve.width=T)
	return(lnew)
}

# Try it out: compare x-axis and y-axis
somedata = tibble(x = runif(n = 100)-0.5, y = runif(n = 100)-0.5)
ggplot(data = somedata, aes(x, y)) +
	geom_point() +
	scale_y_continuous(labels = prettyZero)

Leave a comment...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s