0

I would like to fix the number of decimal places using scientific notation on ggplot2 labels. Here is the code I use:

# data
Model = as.factor(rep(1:3,each=1000))
value = rnorm(3000,mean = 0,sd=0.000001)
test = data.frame(Model=Model,value=value)

# plot
p = ggplot(test, aes(x = value, fill=Model,colour = Model)) +
  geom_density(position="identity", alpha = 0.5,size=1) +
  ggtitle("") +
  theme_bw() +
  theme(plot.title = element_text(size = 14, face = "bold"),
        text = element_text(size = 12),
        axis.line = element_line(colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank()) +
  scale_colour_manual(values = c("#2ca02c","#ff7f0e","#d62728"))+
  scale_fill_manual(values = c("#2ca02c","#ff7f0e","#d62728"))+
  scale_y_continuous(name = "Density",labels = function(x){base::format(x,nsmall=1,scientific=TRUE)})+
  scale_x_continuous(name = "Score",labels = function(x){base::format(x,nsmall=1,scientific=TRUE)})
p

The idea is I want all the lable numbers to be one decimal place using scientific notation. For example, it has to be 1.0e+05 instead of 1e+05. I set nsmall=1 but it seems not work in ggplot2... Any suggestion is appreciated!

Jeffrey
  • 9
  • 2
  • 2
    Your example isn't reproducible, but have a look at `?scales::label_scientific`. – Axeman Jun 05 '20 at 20:56
  • Yes, I tried `scales::label_scientific` and set `nsmall=1` but it doesn't work. I will provide a reproducible example soon. Thank you! – Jeffrey Jun 05 '20 at 21:07
  • Reading `?format` does say that `nsmall` is for "non-scientific formats", so this not working is documented. I'm not sure what a good alternative is though. – Axeman Jun 05 '20 at 21:14
  • Yes... but for some reason `format(c(600000, 13.1), nsmall = 2,scientific=T)` works in R. It just not working in ggplot2... I have provided a reproducible example. – Jeffrey Jun 05 '20 at 21:25
  • `nsmall = 2` isn't doing anything in that example (`format(c(600000, 13.1), nsmall = 2,scientific=T)`). – Axeman Jun 05 '20 at 21:50

0 Answers0