【问题标题】:How to put x-axis in order(Month) in R如何在R中按顺序(月)放置x轴
【发布时间】:2019-04-12 20:47:19
【问题描述】:

我想用月份作图,但 x 轴不按顺序排列,例如“Apr”、“Aug”、“Nov”..... 但我希望 x 轴上的顺序类似于“Jan”、“Feb”、“Mar”........

#change the format of date
date_month <- format(date_1, "%b")
class(date_month)
[1] "character"

head(date_month)
[1] "Jul" "Jul" "Jul" "Jul" "Jul" "Jul"

plot(table(date_month), xlab = "Month", ylab = "count")

我试过了:

x1  <- factor(date_month, levels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",  "Aug", "Sep", "Oct", "Nov","Dec"))
plot(y ~ x1)

和:

plot(table(date_month), xlab = "Month", ylab = "count")
axis(date_month,labels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",  "Aug", "Sep", "Oct", "Nov","Dec"))

根本不起作用。有人可以帮我解决这个问题吗?非常感谢。

【问题讨论】:

    标签: r plot data-science data-analysis


    【解决方案1】:

    在你的代码中使用格式来提取月份 但是使用基本 r 函数months 你会 轻松获得解决方案

    如果你使用format 输出是这样的:

    > head(format(date_month$date, "%b"))
    [1] "Jun" "Feb" "Mar" "Oct" "Oct" "Aug"
    

    months 将完全提取月份名称,如下所示:

    > head(months(date_month$date))
    [1] "June"     "February" "March"    "October"  "October"  "August"  
    

    根据您的代码执行以下操作:

    date_month<-months(date_1)
    date_month<-factor(date_month,levels=month.name)
    

    现在开始尝试。

    示例代码:

    date_month<-list(date=sample(seq(as.Date('2018/01/01'), 
                                  as.Date('2018/11/08'), by="day"), 100))
    
    > head(date_month)
            date
    1 2018-06-13
    2 2018-02-19
    3 2018-03-05
    4 2018-10-29
    5 2018-10-25
    6 2018-08-22
    

    【讨论】:

      【解决方案2】:

      month.name 是一个内置的“常量”,所有月份的名称都是长格式的。要将其与您的数据匹配,请使用 substr() 并仅保留前三个字符。

      date_month <- factor(date_month, levels = substr(month.name, 1, 3))
      

      然后像往常一样绘制它。

      plot(table(date_month), xlab = "Month", ylab = "count")
      

      数据

      set.seed(42)
      date_1 <- as.Date(sample(0:364, 5e5, replace=TRUE), 
                        origin="2018-01-01")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2019-09-09
        相关资源
        最近更新 更多