R:折线图 x值如何按年月顺序显示?

R: Line chart How to display x-value as year and month in proper sequence?

我想按 orders_due 用户每月的数量绘制折线图。 需要显示 month_year 应按顺序排列。

数据集喜欢

User            Due_date 
a               02-10-2017
b               02-02-2017
a               02-08-2017
c               02-08-2017
a               02-08-2017
s               02-06-2017
c               02-06-2017
s               02-06-2017
b               02-06-2017
c               02-11-2017
a               02-11-2017
s               02-11-2017
c               02-01-2017
s               02-01-2017
b               02-01-2017
b               02-10-2017

我正在尝试生成它,但月份顺序不正确。

inv$Month_Due <- inv$Due_Date
day(inv$Month_Due) <- days_in_month(inv$Due.Date)

inv<-inv[order(as.Date(inv$Due_Date, format="%d/%m/%Y")),]
inv$start_year_month <- format(inv$Month_Due, "%Y-%B")


#Chart generate
rpivotTable(inv,  aggregatorName = "Count as Fraction of Total",  rows = "User",  cols = c("start_year_month"),  width = "100%",  height = "200px",rendererName = "Line Chart")

报告显示结果为:

问题是您的变量 start_year_month 是一个字符串(或因子)并按字母顺序排序。

调用后

inv$start_year_month <- format(inv$Month_Due, "%Y-%B")

R 不再 "know "“start_year_month 编码 data.time 信息并将变量用作字符串(=字母排序)。

您可以:

1.(更好的解决方案)将其保留为 data.time 列并将其用于绘图

2.Make 通过使用参数 levels 并以正确的顺序向其传递一个包含 start_year_month 的所有唯一值的向量,将其

2.Make 转换为有序因子。即

inv$start_year_month <- factor(inv$start_year_month, levels=paste(unique(format(inv$Month_Due, "%Y")), month.name, sep="-"))