【问题标题】:ggplot2: Use both scientific notation and full numbersggplot2:同时使用科学记数法和完整数字
【发布时间】:2013-06-03 11:46:39
【问题描述】:

我有一个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

输出:

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

100
1000
10^4
10^5

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

【问题讨论】:

  • 请提供一个可重现的例子。
  • 更改了我的示例代码。

标签: r plot ggplot2 histogram


【解决方案1】:

您可以使用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)

【讨论】:

  • 谢谢,就像一个魅力。不过,我不明白trans_format("log10",math_format(10^.x))(x) 到底做了什么。 trans_format 是否返回一个立即调用的函数?
  • @wnstnsmth 是的,虽然它只能通过调用f 来调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
相关资源
最近更新 更多