Reputation: 9037
For a journal submission, I've been told that my figures can't have leading zeros. For example, take this plot:
df <- data.frame(x = -10:10, y = (-10:10)/10)
ggplot(df, aes(x, y))+
geom_point()
The y-axis has the labels
-1.0 -0.5 0.0 0.5 1.0
I need to produce these labels:
-1.0 -.5 0 .5 1.0
I imagine I'll have to use format_format()
from the scales package, but I haven't seen anything in the various documentation for format
, formatC
and sprintf
that would produce the necessary labels.
Upvotes: 2
Views: 3007
Reputation: 83225
You can write your own function:
no_zero <- function(x) {
y <- sprintf('%.1f',x)
y[x > 0 & x < 1] <- sprintf('.%s',x[x > 0 & x < 1]*10)
y[x == 0] <- '0'
y[x > -1 & x < 0] <- sprintf('-.%s',x[x > -1 & x < 0]*-10)
y
}
and then plot:
ggplot(df, aes(x, y))+
geom_point() +
scale_y_continuous(labels = no_zero)
which gives the desired result:
Upvotes: 6
Reputation: 109874
I have a GitHub package, numform that can do this (I added control over zeros to the f_num
function based on this question):
library(devtools)
library(ggplot2)
install_github('trinker/numform')
df <- data.frame(x = -10:10, y = (-10:10)/10)
ggplot(df, aes(x, y))+
geom_point() +
scale_y_continuous(labels = numform::ff_num(zero = 0))
Upvotes: 5
Reputation: 816
This will work:
ggplot(df, aes(x, y))+
geom_point()+
scale_y_continuous(breaks = c("-1.0" = -1, "-.5"= -0.5, "0" = 0, ".5" = 0.5, "1.0" = 1))
Unfortunately this requires specifying the format manually for each plot; I don't know off the top of my head how to do the formatting automatically.
Upvotes: 4