Search code examples
rggplot2chartsplotlyflexdashboard

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


I want to plot the line chart by number of orders_due to which user monthly. Need Displayed month_year should be in sequence.

Data set like

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

I am try to generate it but month order not getting correct.

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")

Report displayed result as: enter image description here


Solution

  • The problem is that your variable start_year_month is a character string (or factor) and sorted alphabetically.

    After calling

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

    R doesn't "know "anymore" that start_year_month encodes data.time information and uses the variable as if it was a string (= alphabetic sorting).

    You can either:

    1.(Better solution) leave it as a data.time column and use that for plotting

    or

    2.Make it to a ordered factor, by using the parameter levels and passing it a vector with all unique values for start_year_month in the correct order. I.e.

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