ggplot2:使用科学记数法和完整数字

时间:2013-06-03 11:46:40

标签: r plot ggplot2 histogram

我有一个ggplot2图,直方图如下:

  library("ggplot2")
  library("scales")
  df <- data.frame(test = rnorm(1000, 1000, 40000))
  p <- ggplot(df, aes(x = test)) + geom_histogram(colour="black", fill="#FF9999")
  # set themes, axes and labels
  p <- p + theme_minimal() + theme() + xlab("Distance travelled [km]") + ylab("Count of users") 


  # transformation
  p <- p + scale_x_log10(breaks = trans_breaks("log10", function(x) {10^x}),
                       labels = trans_format("log10", math_format(10^.x))
  )

  # plot
  p

输出: enter image description here

我使用scales包将x轴标签显示为10的幂,但实际上,我想将它们显示为十进制数,只要数字低于数字,就说10 ^ 4和10 ^ -4,对于下面的图,这将给出以下轴标签

100
1000
10^4
10^5

我如何在trans_format()中执行此操作,还是有其他更好的解决方案?

1 个答案:

答案 0 :(得分:3)

您可以使用ifelseidentitytrans_format之间进行分支:

f <- function (x) ifelse(log10(x)<4,identity(x),trans_format("log10",math_format(10^.x))(x))
> f(10^(1:6))
[[1]]
[1] 10

[[2]]
[1] 100

[[3]]
[1] 1000

[[4]]
10^`4`

[[5]]
10^`5`

[[6]]
10^`6`

p + scale_x_log10(breaks = trans_breaks("log10", function(x) {10^x}), labels=f)