Reputation: 3123
I am trying to plot data that have week numbers(like 01-2017, 02-2017 and so on[also months like January-2017, February-2017 etc,. & quarters like Q1-2017, Q2-2017]) on x-axis and a integer variable on y-axis.
The problem is, plotly is sorting the x-axis like shown in below picture.
in above picture you can see weeks belonging to 2018 coming before 2017.
in above picture you can see months sorted(November-2017 coming after jan, feb 2018).
I could get dates to get sorted by help from this stackoverflow answer. Here's what I've done to generate week numbers, months and quarters from dates(link to my data):
data <- read.csv("dummy wait times data.csv", header = TRUE)
data$Date <- as.Date(data$Date, "%d-%m-%y")
data$weeks <- format(data$Date, "%U-%Y")
data$months <- format(data$Date, "%B-%Y")
data$quarters <- paste(quarters(data$Date), format(data$Date, "%Y"), sep = "-")
Also, this plot will be in a shiny app after lots of filtration(mean calculated after month, week or quarter being selected). So, my code for plot is:
plot_ly(data = filtered_data(),
# since the column names returned by aggregation function change, let's plot using indexes.
x = ~column_with_some_sort_of_date,
y = ~integer_column,
type = "bar",
# using the reactive department input and splitting the data.
split = ~categorical_column)
[["column_with_some_sort_of_date
" might be weekly or monthly or quarterly based on selectInput
in shiny app.
"categorical_column
" is "Department
" in my data(this has a check box input(checkboxGroupInput
) in shiny app).]]
So, please help me to unsort the dates and plot them. also I'm ready to learn any other interactive plotting library too(ggplotly didn't work).
Upvotes: 0
Views: 2796
Reputation: 107567
Consider generating the time units to factors as format
creates character vectors which is why x-axes sort alphabetically. Factors may translate in plotly as categorical fields. However, first order data frame by Date before assigning factors:
# READ DATA
data <- transform(read.csv("dummy wait times data.csv", header = TRUE),
Date = as.Date(Date, "%d-%m-%y"))
# ORDER DATA FRAME BY DATE
data <- data.frame(with(data, data[order(Date),]),
row.names = NULL)
# ASSIGN ORDERED FACTORS
data <- within(data, {
weeks <- format(Date, "%U-%Y")
weeks <- factor(weeks, levels = unique(weeks))
months <- format(Date, "%B-%Y")
months <- factor(months, levels = unique(months))
quarters <- paste(quarters(Date), format(Date, "%Y"), sep = "-")
quarters <- factor(quarters, levels = unique(quarters))
})
Upvotes: 2