【问题标题】:How to change axis labels from numeric dates to string in ggplot?如何在ggplot中将轴标签从数字日期更改为字符串?
【发布时间】:2018-07-16 23:40:33
【问题描述】:

我有一个简单的箱线图示例:

date.numeric <- c(98,105,110,120,75,35,200,167,365,425,400,398)
age.class <- c("juv","juv","juv","juv","juv","ad","ad","ad","ad","ad","ad","ad")
mytable <- data.frame(date.numeric,age.class)
ggplot(mytable, aes(x=age.class, y=date.numeric)) +
  geom_boxplot()

我的变量 date.numeric 在图中被描述为数字,其中日期数字 1 表示日期 1/1/2015(参考日期)。如何更改 y 轴以“月-年”格式而不是数字格式显示日期?

【问题讨论】:

    标签: r ggplot2 boxplot


    【解决方案1】:

    试试as.Date()

    library(ggplot2)
    date.numeric <- c(98,105,110,120,75,35,200,167,365,425,400,398)
    age.class <- c("juv","juv","juv","juv","juv","ad","ad","ad","ad","ad","ad","ad")
    mytable <- data.frame(date.numeric,age.class)
    
    mytable$date <- (as.Date(date.numeric,origin = "2015/1/1"))
    ggplot(mytable, aes(x=age.class, y=date)) +
      geom_boxplot()
    

    reprex package (v0.2.0.9000) 于 2018 年 7 月 17 日创建。

    【讨论】:

      【解决方案2】:

      尝试创建一个日期偏移变量并将其添加到您的 y 轴。

      date.start <- as.Date('2015-01-01')
      date.numeric <- c(98,105,110,120,75,35,200,167,365,425,400,398)
      age.class <- c("juv","juv","juv","juv","juv","ad","ad","ad","ad","ad","ad","ad")
      mytable <- data.frame(date.numeric,age.class)
      ggplot(mytable, aes(x=age.class, y=date.numeric+date.start)) + geom_boxplot()
      

      然后轴看起来像 2015 年 4 月等。

      【讨论】:

        猜你喜欢
        • 2019-03-25
        • 1970-01-01
        • 1970-01-01
        • 2018-12-08
        • 2020-03-19
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 2023-04-05
        相关资源
        最近更新 更多