【问题标题】:Log axis labels in ggplot2: Show only necessary digits?ggplot2中的日志轴标签:仅显示必要的数字?
【发布时间】:2018-05-18 14:40:57
【问题描述】:

我想在 ggplot2 中制作一个图表,x 轴在 log10 刻度上,标签采用常规而不是科学记数法,小数位数最少。这意味着我想将 0.1 显示为 0.1 而不是 0.10 和 100 显示为 100 而不是 100.00。

我试过了

df = data.frame(x =  c(1:10 %o% 10^(-3:2)), y = rnorm(60))

ggplot(df, aes(x=x, y=y))+
      geom_point()+scale_x_log10(labels=comma)

不幸的是,这显示了许多小数。

@BenBolker 之前回答了类似的question,他的代码适用于没有小数的数字,但如果有小于 1 的数字,它似乎给出与标签 = 逗号相同的结果。

plain <- function(x,...) {
  format(x, ..., scientific = FALSE, trim = TRUE)
}

ggplot(df, aes(x=x, y=y))+
  geom_point()+scale_x_log10(labels=plain)

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    plain 中添加drop0trailing = TRUE

    plain <- function(x,...) {
      format(x, ..., scientific = FALSE, drop0trailing = TRUE)
    }
    

    要查看漂亮打印的其他选项,请参阅?format

    【讨论】:

    • 整洁。那很快!谢谢!
    • 使用“scale_x_continous(trans="log")”而不是“scale_x_log10()”时如何进行?
    【解决方案2】:

    只是想补充一点,而不是创建一个单独的 plain 函数,我们还可以使用 scales 包,它为 ggplot2 缩放提供了一套很好的工具,并使格式化日志轴标签变得轻而易举。下面是可重现的代码,展示了日志轴标签的一些格式化选项:

    library(ggplot2)
    library(scales)
    library(patchwork)
    
    df <- data.frame(x =  c(1:10 %o% 10^(-3:3)), y = rnorm(70))
    
    base <- ggplot(df, aes(x, y)) + 
      geom_point()
    
    p1 <- base + scale_x_log10(labels = label_number(drop0trailing = TRUE))
    p2 <- base + scale_x_log10(labels = label_comma(drop0trailing = TRUE)) 
    p3 <- base + 
      scale_x_log10(
        labels = label_dollar(drop0trailing = TRUE),
        # prevents axis label from going off the chart
        expand = expansion(mult = c(0.05, .06)) 
      )
    p4 <- base + scale_x_log10(labels = trans_format("log10", label_math()))
    
    (p1 + p2 + p3 + p4) + plot_annotation(tag_levels = "1", tag_prefix = "p")
    

    reprex package (v2.0.0) 于 2021-05-16 创建

    【讨论】:

    • 这是一个非常好的答案,我也了解了%o%
    • @tjebo,其实我也是从问题本身了解到%o%运算符的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多