【问题标题】:how to change x axis labels so that its shown in 0-10, 10-20, 20-30 format etc如何更改 x 轴标签,使其以 0-10、10-20、20-30 等格式显示
【发布时间】:2021-01-05 08:06:25
【问题描述】:

我正在尝试更改 x 轴上的 x 标签在 ggplot2 直方图中的表示方式,以便显示为 0-10、10-20、20-30,而不是 0、10、20、30, 30-40等

我知道这可以手动完成,但我想知道是否有更简单的方法。

【问题讨论】:

    标签: r ggplot2 axis


    【解决方案1】:

    假设你有这样的数据:

    set.seed(123)
    vec <- sample(1:50, 100, replace = TRUE)
    df <- data.frame(vec)
    

    而且您已经有了group 列,您可以创建labels 列。

    library(dplyr)
    library(ggplot2)
    
    df %>% 
      mutate(group = ceiling(vec/10) * 10, 
             labels = paste(group-10, group, sep = '-')) -> df1
    

    并在geom_histogram 中使用scale_x_continuous

    ggplot(df1) + aes(group) + 
      geom_histogram(bins = 5) +
      scale_x_continuous(breaks = unique(df1$group), labels = unique(df1$labels))
    

    【讨论】:

    • 谢谢,但是有没有办法直接在 ggplot2 中执行此操作而不是变异?
    • @newbie 当然可以,但是您应该以可复制的格式提供您的数据,以便我们可以复制粘贴。您在问题中没有提供有关数据外观的信息。阅读how to give a reproducible example
    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多